YYText 库学习总结

YYText 是一个强大的富文本库.在iOS开发中经常会用到富文本。我们常用到的效果如下图所示:

yytext.png

下面我们来看看各个功能的实现:
先创建一个可变属性字符串:

    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:DaoXiang];
    [text yy_setFont:[UIFont systemFontOfSize:20] range:text.yy_rangeOfAll];//字体
    text.yy_lineSpacing = 20;//行间距

DaoXiang是一个宏定义字符串,

DaoXiang.png

字体、颜色、文字间距


实现:

NSRange range0 = [[text string] rangeOfString:@"对这个世界如果你有太多的抱怨" options:NSCaseInsensitiveSearch];
//字体
[text yy_setFont:[UIFont systemFontOfSize:25] range:range0];
//文字颜色
[text yy_setColor:[UIColor purpleColor] range:range0];
//文字间距
[text yy_setKern:@(2) range:range0];

效果:

字体、颜色、文字间距.png

文字描边(空心字)


实现代码

NSRange range1 = [[text string] rangeOfString:@"跌倒了 就不敢继续往前走" options:NSCaseInsensitiveSearch];
//文字描边(空心字)默认黑色,必须设置width
[text yy_setStrokeColor:[UIColor orangeColor] range:range1];
[text yy_setStrokeWidth:@(2) range:range1];

效果


文字描边

删除样式、下划线


实现代码

NSRange range2 = [[text string] rangeOfString:@"为什麼 人要这麼的脆弱 堕落" options:NSCaseInsensitiveSearch];
        
YYTextDecoration *decoration = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                       width:@(1)
                                                                       color:[UIColor blueColor]];
//删除样式
[text yy_setTextStrikethrough:decoration range:range2];
//下划线
[text yy_setTextUnderline:decoration range:range2];

效果

删除样式、下划线

边框


实现代码

NSRange range3 = [[text string] rangeOfString:@"请你打开电视看看 多少人" options:NSCaseInsensitiveSearch];
    
//边框
YYTextBorder *border = [YYTextBorder new];
border.strokeColor = [UIColor colorWithRed:1.000 green:0.029 blue:0.651 alpha:1.000];
border.strokeWidth = 3;
border.lineStyle = YYTextLineStylePatternCircleDot;
border.cornerRadius = 3;
border.insets = UIEdgeInsetsMake(0, -2, 0, -2);
    
[text yy_setTextBorder:border range:range3];

效果

边框

阴影


实现代码

NSRange range4 = [[text string] rangeOfString:@"为生命在努力勇敢的走下去" options:NSCaseInsensitiveSearch];

//阴影
NSShadow *shadow = [[NSShadow alloc] init];
[shadow setShadowColor:[UIColor redColor]];
[shadow setShadowBlurRadius:1.0];
[shadow setShadowOffset:CGSizeMake(2, 2)];
[text yy_setShadow:shadow range:range4];

效果

阴影

文本内阴影


实现代码

NSRange range5 = [[text string] rangeOfString:@"我们是不是该知足" options:NSCaseInsensitiveSearch];

//文本内阴影
YYTextShadow *shadow = [YYTextShadow new];
shadow.color = [UIColor redColor];
shadow.offset = CGSizeMake(0, 2);
shadow.radius = 1;
[text yy_setTextInnerShadow:shadow range:range5];

效果

文本内阴影

多重阴影


实现代码

//多重阴影
NSRange range6 = [[text string] rangeOfString:@"珍惜一切就算没有拥有" options:NSCaseInsensitiveSearch];


YYTextShadow *shadow = [YYTextShadow new];
shadow.color = [UIColor redColor];
shadow.offset = CGSizeMake(0, -1);
shadow.radius = 1.5;
YYTextShadow *subShadow = [YYTextShadow new];
subShadow.color = [UIColor greenColor];
subShadow.offset = CGSizeMake(0, 1);
subShadow.radius = 1.5;
shadow.subShadow = subShadow;
[text yy_setTextShadow:shadow range:range6];

YYTextShadow *shadow1 = [YYTextShadow new];
shadow1.color = [UIColor orangeColor];
shadow1.offset = CGSizeMake(0, 2);
shadow1.radius = 1;
[text yy_setTextInnerShadow:shadow range:range6];

效果

多重阴影

简单文本高亮


实现代码

//文本高亮简单版
NSRange range8 = [[text string] rangeOfString:@"随著稻香河流继续奔跑" options:NSCaseInsensitiveSearch];
[text yy_setTextHighlightRange:range8
                         color:[UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000]
               backgroundColor:[UIColor colorWithWhite:0.000 alpha:0.220]
                     tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                         [AppUtility showMessage:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
                     }];

效果

简单文本高亮

//文本高亮pro


实现代码

//文本高亮pro
UIColor *colorNormal = [UIColor colorWithRed:0.093 green:0.492 blue:1.000 alpha:1.000];
UIColor *colorHighlight = [UIColor purpleColor];

NSRange range9 = [[text string] rangeOfString:@"微微笑 小时候的梦我知道" options:NSCaseInsensitiveSearch];


YYTextDecoration *decorationNomal = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                    width:@(1)
                                                                    color:colorNormal];
YYTextDecoration *decorationHighlight = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                        width:@(1)
                                                                        color:colorHighlight];
//未点击时颜色
[text yy_setColor:colorNormal range:range9];
//未点击时下划线
[text yy_setTextUnderline:decorationNomal range:range9];

//点击后的状态
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setColor:colorHighlight];
[highlight setUnderline:decorationHighlight];
highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
    [AppUtility showMessage:[NSString stringWithFormat:@"Tap: %@",[text.string substringWithRange:range]]];
};
[text yy_setTextHighlight:highlight range:range9];

效果

文本高亮pro

@,#,email,link


实现代码


// 高亮状态的背景
YYTextBorder *highlightBorder = [YYTextBorder new];
highlightBorder.insets = UIEdgeInsetsMake(-2, 0, -2, 0);
highlightBorder.cornerRadius = 3;
highlightBorder.fillColor = [UIColor greenColor];

//@用户名称
NSArray *resultAt= [[Utility regexAt] matchesInString:text.string options:kNilOptions range:text.yy_rangeOfAll];

for (NSTextCheckingResult *at in resultAt)
{
    if (at.range.location == NSNotFound && at.range.length <= 1)
    {
        continue;
    }
    
    if ([text yy_attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil)
    {
        [text yy_setColor:[UIColor blueColor] range:at.range];
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setBackgroundBorder:highlightBorder];
        // 数据信息,用于稍后用户点击
        NSString *atName = [text.string substringWithRange:NSMakeRange(at.range.location + 1, at.range.length - 1)];
        highlight.userInfo = @{@"linkValue" : atName,@"linkType":@(LinkTypeAt)};
        [text yy_setTextHighlight:highlight range:at.range];
    }
}

//#话题#
NSArray *resultTopic = [[Utility regexTopic] matchesInString:text.string options:kNilOptions range:text.yy_rangeOfAll];

for (NSTextCheckingResult *at in resultTopic)
{
    if (at.range.location == NSNotFound && at.range.length <= 1)
    {
        continue;
    }
    
    if ([text yy_attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil)
    {
        [text yy_setColor:[UIColor blueColor] range:at.range];
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setBackgroundBorder:highlightBorder];
        // 数据信息,用于稍后用户点击
        highlight.userInfo = @{@"linkValue" : [text.string substringWithRange:NSMakeRange(at.range.location, at.range.length)],@"linkType":@(LinkTypeTopic)};
        [text yy_setTextHighlight:highlight range:at.range];
    }
}

//email
NSArray *resultEmail = [[Utility regexEmail] matchesInString:text.string options:kNilOptions range:text.yy_rangeOfAll];

for (NSTextCheckingResult *at in resultEmail)
{
    if (at.range.location == NSNotFound && at.range.length <= 1)
    {
        continue;
    }
    
    if ([text yy_attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil)
    {
        [text yy_setColor:[UIColor blueColor] range:at.range];
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setBackgroundBorder:highlightBorder];
        // 数据信息,用于稍后用户点击
        highlight.userInfo = @{@"linkValue" : [text.string substringWithRange:NSMakeRange(at.range.location, at.range.length)],@"linkType":@(LinkTypeEmail)};
        [text yy_setTextHighlight:highlight range:at.range];
    }
}

//link
NSArray *resultLink = [[Utility regexUrl] matchesInString:text.string options:kNilOptions range:text.yy_rangeOfAll];

for (NSTextCheckingResult *at in resultLink)
{
    if (at.range.location == NSNotFound && at.range.length <= 1)
    {
        continue;
    }
    
    if ([text yy_attribute:YYTextHighlightAttributeName atIndex:at.range.location] == nil)
    {
        [text yy_setColor:[UIColor blueColor] range:at.range];
        // 高亮状态
        YYTextHighlight *highlight = [YYTextHighlight new];
        [highlight setBackgroundBorder:highlightBorder];
        // 数据信息,用于稍后用户点击
        highlight.userInfo = @{@"linkValue" : [text.string substringWithRange:NSMakeRange(at.range.location, at.range.length)],@"linkType":@(LinkTypeURL)};
        [text yy_setTextHighlight:highlight range:at.range];
    }
}

效果

@,#,email,link

以话题为例,简单说明一下:首先用正则来查出所有话题,然后再将话题部分设置高亮状态以及数据信息,这些信息在用户点击时会用到。后面会说到如何处理点击,别急。

添加gif动画

实现代码

YYImage *image = [YYImage imageNamed:@"zuqiu"];
image.preloadAllAnimatedImageFrames = YES;
YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:image];
imageView.autoPlayAnimatedImage = NO;
[imageView startAnimating];

NSMutableAttributedString *attachText = [NSMutableAttributedString yy_attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:[UIFont systemFontOfSize:16] alignment:YYTextVerticalAlignmentBottom];
[text appendAttributedString:attachText];

添加普通图片直接使用UIImage和UIImageView就可以了。

布局


实现代码

CGSize size = CGSizeMake(SCREEN_WIDTH, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size text:text];
    
// 获取文本显示位置和大小
//layout.textBoundingRect; // get bounding rect
//layout.textBoundingSize; // get bounding size

可以由YYTextLayout获取文本的bonding rectsize

YYLabel添加


实现代码

YYLabel *label = [YYLabel new];
label.highlightTapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
    if ([self.clickDelegate respondsToSelector:@selector(label:tapHighlight:inRange:)])
    {
        YYTextHighlight *highlight = [text yy_attribute:YYTextHighlightAttributeName atIndex:range.location];
        [self.clickDelegate label:(YYLabel *)containerView tapHighlight:highlight inRange:range];
    }
};
label.frame = CGRectMake(0, 0, SCREEN_WIDTH, layout.textBoundingSize.height);
label.textAlignment = NSTextAlignmentCenter;
label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
label.numberOfLines = 0;
label.backgroundColor = RGBCOLOR(246, 246, 246);
label.textLayout = layout;
[self addSubview:label];
```
这里有个属性`highlightTapAction`就是用来处理点击高亮文字事件的,在这里,我定义了一个delegate:
```
@protocol YYHiglightTextClickDelegate <NSObject>

- (void)label:(YYLabel *)label
 tapHighlight:(YYTextHighlight *)highlight
      inRange:(NSRange)textRange;

@end
```

只要实现这个delegate就能方便的处理点击各种高亮文字的事件。`YYTextHighlight `里面包含了一个userInfo,包含了很多需要处理的信息,通过它,能够很容易的处理点击事件,我这里在UIViewController中做了一个实现:
```
#pragma mark - YYHiglightTextClickDelegate
- (void)label:(YYLabel *)label
 tapHighlight:(YYTextHighlight *)highlight
      inRange:(NSRange)textRange
{
    NSDictionary *info = highlight.userInfo;
    LinkType linkType = [info[@"linkType"] integerValue];
    NSString *linkValue = info[@"linkValue"];
    switch (linkType) {
        case LinkTypeAt:
        {
            [AppUtility showMessage:[NSString stringWithFormat:@"选中at:%@",linkValue]];
        }
            break;
        case LinkTypeTopic:
        {
            [AppUtility showMessage:[NSString stringWithFormat:@"选中话题:%@",linkValue]];
        }
            break;
        case LinkTypeEmail:
        {
            [AppUtility showMessage:[NSString stringWithFormat:@"选中email:%@",linkValue]];
        }
            break;
        case LinkTypeURL:
        {
            [AppUtility showMessage:[NSString stringWithFormat:@"选中url:%@",linkValue]];
        }
            break;
        case LinkTypePhoneNum:
        {
            [AppUtility showMessage:[NSString stringWithFormat:@"选中phone:%@",linkValue]];
        }
            break;
        default:
            break;
    }
}
```
我在userInfo中传入了两对键值:
####表情
---
实现代码
```
NSMutableDictionary *mapper = [NSMutableDictionary new];
mapper[@":smile:"] = [self imageWithName:@"002"];
mapper[@":cool:"] = [self imageWithName:@"013"];
mapper[@":biggrin:"] = [self imageWithName:@"047"];
mapper[@":arrow:"] = [self imageWithName:@"007"];
mapper[@":confused:"] = [self imageWithName:@"041"];
mapper[@":cry:"] = [self imageWithName:@"010"];
mapper[@":wink:"] = [self imageWithName:@"085"];
mapper[@":zuqiu:"] = [self imageWithName:@"zuqiu"];

YYTextSimpleEmoticonParser *parser = [YYTextSimpleEmoticonParser new];
parser.emoticonMapper = mapper;

YYTextLinePositionSimpleModifier *mod = [YYTextLinePositionSimpleModifier new];
mod.fixedLineHeight = 22;
```
`YYLabel`已经实现了一个简单的表情解析器`YYTextSimpleEmoticonParser `,你只需要设置一下映射器`emoticonMapper`就好.

然后把解析器和modifier传给`YYLabel`.
最后将文本传给`attributedText`
```
label.textParser = parser;
label.linePositionModifier = mod;
label.attributedText = text;
```
`linePositionModifier`是在文本发生变化时才需要的属性,一般YYTextView用的多,比如修改一个文本之后,整个文本发生了变化,就需要这个属性值。

表情资源来自YYText,可以下载源码获得。

另外我写了个小[demo](https://github.com/flowyears/AttributeTextDemo),包含YYLabel,YYTextView以及TTTAttributedLabel的简单实用。

[TTTAttributedLabel简单使用](http://www.jianshu.com/p/b457a49fac3d)简单的描述了TTTAttributedLabel的使用,并且在最后将YYLabel,YYTextView以及TTTAttributedLabel三者的功能做了一个简单的比较。


在学习的过程中发现有几个属性无效,一个是斜体,一个是文字背景色,如果有知道怎么实现的小伙伴请告诉我一下,谢谢。


以上只是一个简单的使用。这里有一篇更深层次的剖析:[YYKit之YYText](http://www.cnblogs.com/lujianwenance/p/5716804.html).

end.
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,614评论 4 59
  • WebSocket-Swift Starscream的使用 WebSocket 是 HTML5 一种新的协议。它实...
    香橙柚子阅读 22,958评论 8 183
  • 某天和堂哥打电话,刚接通电话,他压低了嗓门,轻声轻语地跟我说,要到房间外面去接电话。 “为什么还要到外面去接电话?...
    紫玉葡萄不吐葡萄阅读 220评论 0 2
  • 从软件园下班,到英郡吃晚饭,需要步行约3里,路过两个车站,一条八车道马路。过马路的时候总会看到道旁气势磅礴的软件园...
    刘想说阅读 150评论 0 1
  • 没有人会理解,此刻的你是有多无助。
    aa9c92d2e907阅读 115评论 0 1