YYText 是一個(gè)強(qiáng)大的富文本庫(kù).在iOS開發(fā)中經(jīng)常會(huì)用到富文本。我們常用到的效果如下圖所示:

yytext.png
下面我們來(lái)看看各個(gè)功能的實(shí)現(xiàn):
先創(chuàng)建一個(gè)可變屬性字符串:
NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:DaoXiang];
[text yy_setFont:[UIFont systemFontOfSize:20] range:text.yy_rangeOfAll];//字體
text.yy_lineSpacing = 20;//行間距
DaoXiang是一個(gè)宏定義字符串,

DaoXiang.png
字體、顏色、文字間距
實(shí)現(xiàn):
NSRange range0 = [[text string] rangeOfString:@"對(duì)這個(gè)世界如果你有太多的抱怨" options:NSCaseInsensitiveSearch];
//字體
[text yy_setFont:[UIFont systemFontOfSize:25] range:range0];
//文字顏色
[text yy_setColor:[UIColor purpleColor] range:range0];
//文字間距
[text yy_setKern:@(2) range:range0];
效果:

字體、顏色、文字間距.png
文字描邊(空心字)
實(shí)現(xiàn)代碼
NSRange range1 = [[text string] rangeOfString:@"跌倒了 就不敢繼續(xù)往前走" options:NSCaseInsensitiveSearch];
//文字描邊(空心字)默認(rèn)黑色,必須設(shè)置width
[text yy_setStrokeColor:[UIColor orangeColor] range:range1];
[text yy_setStrokeWidth:@(2) range:range1];
效果

文字描邊
刪除樣式、下劃線
實(shí)現(xiàn)代碼
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];
效果

刪除樣式、下劃線
邊框
實(shí)現(xiàn)代碼
NSRange range3 = [[text string] rangeOfString:@"請(qǐng)你打開電視看看 多少人" 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];
效果

邊框
陰影
實(shí)現(xiàn)代碼
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];
效果

陰影
文本內(nèi)陰影
實(shí)現(xiàn)代碼
NSRange range5 = [[text string] rangeOfString:@"我們是不是該知足" options:NSCaseInsensitiveSearch];
//文本內(nèi)陰影
YYTextShadow *shadow = [YYTextShadow new];
shadow.color = [UIColor redColor];
shadow.offset = CGSizeMake(0, 2);
shadow.radius = 1;
[text yy_setTextInnerShadow:shadow range:range5];
效果

文本內(nèi)陰影
多重陰影
實(shí)現(xiàn)代碼
//多重陰影
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];
效果

多重陰影
簡(jiǎn)單文本高亮
實(shí)現(xiàn)代碼
//文本高亮簡(jiǎn)單版
NSRange range8 = [[text string] rangeOfString:@"隨著稻香河流繼續(xù)奔跑" 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]]];
}];
效果

簡(jiǎn)單文本高亮
//文本高亮pro
實(shí)現(xiàn)代碼
//文本高亮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:@"微微笑 小時(shí)候的夢(mèng)我知道" options:NSCaseInsensitiveSearch];
YYTextDecoration *decorationNomal = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
width:@(1)
color:colorNormal];
YYTextDecoration *decorationHighlight = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
width:@(1)
color:colorHighlight];
//未點(diǎn)擊時(shí)顏色
[text yy_setColor:colorNormal range:range9];
//未點(diǎn)擊時(shí)下劃線
[text yy_setTextUnderline:decorationNomal range:range9];
//點(diǎn)擊后的狀態(tài)
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
實(shí)現(xiàn)代碼
// 高亮狀態(tài)的背景
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];
// 高亮狀態(tài)
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setBackgroundBorder:highlightBorder];
// 數(shù)據(jù)信息,用于稍后用戶點(diǎn)擊
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];
// 高亮狀態(tài)
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setBackgroundBorder:highlightBorder];
// 數(shù)據(jù)信息,用于稍后用戶點(diǎn)擊
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];
// 高亮狀態(tài)
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setBackgroundBorder:highlightBorder];
// 數(shù)據(jù)信息,用于稍后用戶點(diǎn)擊
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];
// 高亮狀態(tài)
YYTextHighlight *highlight = [YYTextHighlight new];
[highlight setBackgroundBorder:highlightBorder];
// 數(shù)據(jù)信息,用于稍后用戶點(diǎn)擊
highlight.userInfo = @{@"linkValue" : [text.string substringWithRange:NSMakeRange(at.range.location, at.range.length)],@"linkType":@(LinkTypeURL)};
[text yy_setTextHighlight:highlight range:at.range];
}
}
效果

@,#,email,link
以話題為例,簡(jiǎn)單說明一下:首先用正則來(lái)查出所有話題,然后再將話題部分設(shè)置高亮狀態(tài)以及數(shù)據(jù)信息,這些信息在用戶點(diǎn)擊時(shí)會(huì)用到。后面會(huì)說到如何處理點(diǎn)擊,別急。
添加gif動(dòng)畫
實(shí)現(xiàn)代碼
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就可以了。
布局
實(shí)現(xiàn)代碼
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 rect和size。
YYLabel添加
實(shí)現(xiàn)代碼
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];
```
這里有個(gè)屬性`highlightTapAction`就是用來(lái)處理點(diǎn)擊高亮文字事件的,在這里,我定義了一個(gè)delegate:
```
@protocol YYHiglightTextClickDelegate <NSObject>
- (void)label:(YYLabel *)label
tapHighlight:(YYTextHighlight *)highlight
inRange:(NSRange)textRange;
@end
```
只要實(shí)現(xiàn)這個(gè)delegate就能方便的處理點(diǎn)擊各種高亮文字的事件。`YYTextHighlight `里面包含了一個(gè)userInfo,包含了很多需要處理的信息,通過它,能夠很容易的處理點(diǎn)擊事件,我這里在UIViewController中做了一個(gè)實(shí)現(xiàn):
```
#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中傳入了兩對(duì)鍵值:
####表情
---
實(shí)現(xiàn)代碼
```
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`已經(jīng)實(shí)現(xiàn)了一個(gè)簡(jiǎn)單的表情解析器`YYTextSimpleEmoticonParser `,你只需要設(shè)置一下映射器`emoticonMapper`就好.
然后把解析器和modifier傳給`YYLabel`.
最后將文本傳給`attributedText`
```
label.textParser = parser;
label.linePositionModifier = mod;
label.attributedText = text;
```
`linePositionModifier`是在文本發(fā)生變化時(shí)才需要的屬性,一般YYTextView用的多,比如修改一個(gè)文本之后,整個(gè)文本發(fā)生了變化,就需要這個(gè)屬性值。
表情資源來(lái)自YYText,可以下載源碼獲得。
另外我寫了個(gè)小[demo](https://github.com/flowyears/AttributeTextDemo),包含YYLabel,YYTextView以及TTTAttributedLabel的簡(jiǎn)單實(shí)用。
[TTTAttributedLabel簡(jiǎn)單使用](http://m.itdecent.cn/p/b457a49fac3d)簡(jiǎn)單的描述了TTTAttributedLabel的使用,并且在最后將YYLabel,YYTextView以及TTTAttributedLabel三者的功能做了一個(gè)簡(jiǎn)單的比較。
在學(xué)習(xí)的過程中發(fā)現(xiàn)有幾個(gè)屬性無(wú)效,一個(gè)是斜體,一個(gè)是文字背景色,如果有知道怎么實(shí)現(xiàn)的小伙伴請(qǐng)告訴我一下,謝謝。
以上只是一個(gè)簡(jiǎn)單的使用。這里有一篇更深層次的剖析:[YYKit之YYText](http://www.cnblogs.com/lujianwenance/p/5716804.html).
end.