iOS YYText 使用詳解

簡介

YYText 是一個強(qiáng)大的富文本庫.在iOS開發(fā)中經(jīng)常會用到富文本。

下面我們來看看各個功能的實(shí)現(xiàn):
先創(chuàng)建一個可變屬性字符串:

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

DaoXiang是一個宏定義字符串,

image

字體、顏色、文字間距


實(shí)現(xiàn):

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];

效果:

image

文字描邊(空心字)


實(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];

效果

image

刪除樣式、下劃線


實(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];

效果

image

邊框


實(shí)現(xiàn)代碼

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];

效果

image

陰影


實(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];

效果

image

文本內(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];

效果

image

多重陰影


實(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];

效果

image

簡單文本高亮


實(shí)現(xià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]]];
                     }];

效果

image

//文本高亮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:@"微微笑 小時候的夢我知道" options:NSCaseInsensitiveSearch];

YYTextDecoration *decorationNomal = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                    width:@(1)
                                                                    color:colorNormal];
YYTextDecoration *decorationHighlight = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                                                        width:@(1)
                                                                        color:colorHighlight];
//未點(diǎn)擊時顏色
[text yy_setColor:colorNormal range:range9];
//未點(diǎn)擊時下劃線
[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];

效果

image

@,#,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];
    }
}

效果

image

以話題為例,簡單說明一下:首先用正則來查出所有話題,然后再將話題部分設(shè)置高亮狀態(tài)以及數(shù)據(jù)信息,這些信息在用戶點(diǎn)擊時會用到。后面會說到如何處理點(diǎn)擊,別急。

添加gif動畫

實(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 rectsize。

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];

這里有個屬性highlightTapAction就是用來處理點(diǎn)擊高亮文字事件的,在這里,我定義了一個delegate:

@protocol YYHiglightTextClickDelegate <NSObject>

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

@end

只要實(shí)現(xiàn)這個delegate就能方便的處理點(diǎn)擊各種高亮文字的事件。YYTextHighlight里面包含了一個userInfo,包含了很多需要處理的信息,通過它,能夠很容易的處理點(diǎn)擊事件,我這里在UIViewController中做了一個實(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中傳入了兩對鍵值:

表情


實(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)了一個簡單的表情解析器YYTextSimpleEmoticonParser,你只需要設(shè)置一下映射器emoticonMapper就好.

然后把解析器和modifier傳給YYLabel.
最后將文本傳給attributedText

label.textParser = parser;
label.linePositionModifier = mod;
label.attributedText = text;

linePositionModifier是在文本發(fā)生變化時才需要的屬性,一般YYTextView用的多,比如修改一個文本之后,整個文本發(fā)生了變化,就需要這個屬性值。

表情資源來自YYText,可以下載源碼獲得。

另外我寫了個小demo,包含YYLabel,YYTextView以及TTTAttributedLabel的簡單實(shí)用。

TTTAttributedLabel簡單使用簡單的描述了TTTAttributedLabel的使用,并且在最后將YYLabel,YYTextView以及TTTAttributedLabel三者的功能做了一個簡單的比較。

在學(xué)習(xí)的過程中發(fā)現(xiàn)有幾個屬性無效,一個是斜體,一個是文字背景色,如果有知道怎么實(shí)現(xiàn)的小伙伴請告訴我一下,謝謝。

以上只是一個簡單的使用。這里有一篇更深層次的剖析:YYKit之YYText.

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容