1. 程式人生 > >YYText 庫學習總結

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.

 



作者:0o凍僵的企鵝o0
連結:https://www.jianshu.com/p/60aee32ade55
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。