富文本處理

YYText參考文檔
TTTAttributedLabel參考文檔
富文本的處理原生文案略顯麻煩文章鏈接

相比而言,YYText使用簡單且功能強大鞍陨,YYLabel 設置字體樣式更方便簡潔蒿囤。另外TTTAttributedLabel也挺不錯的。

YYText

基礎用法

    //基本用法和UILabel相似
    YYLabel *label = [[YYLabel alloc]init];
    label.frame = CGRectMake(0, 0, 200, 200);
    label.center = self.view.center;
    label.numberOfLines = 2;
    label.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:label];

屬性文本

  NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:@"Change the fucking world"];
  //字體    
  str.yy_font = [UIFont systemFontOfSize:20];
 //顏色
  str.yy_color = [UIColor orangeColor];
  [str yy_setColor:[UIColor greenColor] range:NSMakeRange(7, 4)];

   //也可以直接搜索相應文字改變屬性
   //NSRange range = [[text string] rangeOfString:@"對這個世界如果你有太多的抱怨" 
   //                                      options:NSCaseInsensitiveSearch];

  //行間距
  str.yy_lineSpacing =10;
  //首行縮進
  str.yy_firstLineHeadIndent = 10;

  //文字描邊(空心字)默認黑色
  //必須設置width
  [text yy_setStrokeColor:[UIColor orangeColor] ];
  [text yy_setStrokeWidth:@(2) ];

  //文字裝飾
   YYTextDecoration * decoration 
    = [YYTextDecoration decorationWithStyle:YYTextLineStyleSingle
                                      width:@(1)
                                       color:[UIColor blueColor]];
  //刪除樣式
  [text yy_setTextStrikethrough:decoration 
                          range:range];
  //下劃線
  [text yy_setTextUnderline:decoration 
                      range:range];

  //陰影
  NSShadow *shadow = [[NSShadow alloc]init];
  shadow.shadowColor = [UIColor grayColor];
  shadow.shadowOffset = CGSizeMake(1, 1.5);
  shadow.radius = 5;
  str.yy_shadow  = shadow;
  
  //文本內陰影
  YYTextShadow *shadow = [YYTextShadow new];
  shadow.color = [UIColor redColor];
  shadow.offset = CGSizeMake(0, 2);
  shadow.radius = 1;
  [str yy_setTextInnerShadow:shadow ];



  //背景框
  //多行顯示時效果會不太如愿          
  str.yy_textBorder = [ YYTextBorder borderWithLineStyle:YYTextLineStylePatternCircleDot
                                               lineWidth:1
                                             strokeColor:[UIColor greenColor]];
  str.yy_textBorder.cornerRadius = 3;
  str.yy_textBorder.insets = UIEdgeInsetsMake(0, -2, 0, -2);
  

#pragma mark - 可點擊高亮顯示
  
 [str yy_setTextHighlightRange:range
                       color:[UIColorr redColor]
             backgroundColor:[UIColor greenColor]
                   tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                      //點擊事件
                   }];
  
  //一定要放在最后
  label.attributedText = str;


}

YYAttachment

    NSMutableAttributedString *text = [NSMutableAttributedString new];
    UIFont *font = [UIFont systemFontOfSize:16];
    {
        NSString *title = @"This is UIImage attachment:";
        [text appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:nil]];
        //壓縮
        UIImage *image = [UIImage imageNamed:@"dribbble64_imageio"];
        image = [UIImage imageWithCGImage:image.CGImage 
                                    scale:2 
                              orientation:UIImageOrientationUp];
        
        NSMutableAttributedString *attachText
        = [NSMutableAttributedString yy_attachmentStringWithContent:image
                                                        contentMode:UIViewContentModeCenter
                                                     attachmentSize:image.size
                                                        alignToFont:font
                                                          alignment:YYTextVerticalAlignmentCenter];
        [text appendAttributedString:attachText];
        [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
    }
    {
        NSString *title = @"This is UIView attachment: ";
        [text appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:nil]];
        
        UISwitch *switcher = [UISwitch new];
        [switcher sizeToFit];
        
        NSMutableAttributedString *attachText 
        = [NSMutableAttributedString yy_attachmentStringWithContent:switcher 
                                                        contentMode:UIViewContentModeCenter 
                                                     attachmentSize:switcher.size
                                                        alignToFont:font 
                                                          alignment:YYTextVerticalAlignmentCenter];
        [text appendAttributedString:attachText];
        [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
    }
    {   
        YYImage *image = [YYImage imageNamed:@"pia"];
        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:font
                                                          alignment:YYTextVerticalAlignmentBottom];
        [text appendAttributedString:attachText];
        [text appendAttributedString:[[NSAttributedString alloc] initWithString:@"\n" attributes:nil]];
    }

YYTextLayout

NSAttributedString *text = ...
CGSize size = CGSizeMake(100, CGFLOAT_MAX);
YYTextLayout *layout = [YYTextLayout layoutWithContainerSize:size 
                                                        text:text];
    
// get text bounding
layout.textBoundingRect; // get bounding rect
layout.textBoundingSize; // get bounding size
    
 // query text layout
[layout lineIndexForPoint:CGPointMake(10,10)];
[layout closestLineIndexForPoint:CGPointMake(10,10)];
[layout closestPositionToPoint:CGPointMake(10,10)];
[layout textRangeAtPoint:CGPointMake(10,10)];
[layout rectForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
[layout selectionRectsForRange:[YYTextRange rangeWithRange:NSMakeRange(10,2)]];
    
// text layout display
YYLabel *label = [YYLabel new];
label.size = layout.textBoundingSize;
label.textLayout = layout;

YYTextRubyAnnotation

    NSMutableAttributedString *one = [[NSMutableAttributedString alloc] initWithString:@"這是用漢語寫的一段文字歉眷。"];
    one.yy_font = [UIFont boldSystemFontOfSize:30];

    YYTextRubyAnnotation *ruby;
    ruby = [YYTextRubyAnnotation new];
    ruby.textBefore = @"hàn y?";
    [one yy_setTextRubyAnnotation:ruby 
                            range:[one.string rangeOfString:@"漢語"]];
    
    ruby = [YYTextRubyAnnotation new];
    ruby.textBefore = @"wén";
    [one yy_setTextRubyAnnotation:ruby range:[one.string rangeOfString:@"文"]];
    
    ruby = [YYTextRubyAnnotation new];
    ruby.textBefore = @"zì";
    ruby.alignment = kCTRubyAlignmentCenter;
    [one yy_setTextRubyAnnotation:ruby range:[one.string rangeOfString:@"字"]];
    
    YYLabel *label = [YYLabel new];
    label.backgroundColor = [UIColor whiteColor];
    label.attributedText = one;
    label.frame = CGRectMake(0, 10, self.view.frame.size.width, 200);
    label.textAlignment = NSTextAlignmentCenter;
    label.textVerticalAlignment = YYTextVerticalAlignmentCenter;
    label.numberOfLines = 1;
    [self.view addSubview:label];

TTTAttributed

   //也可以是NSString字符串
    NSMutableAttributedString *attString
    = [[NSMutableAttributedString alloc] initWithString:@"對這個世界如果你有太多的抱怨 \n跌倒了 就不敢繼續(xù)往前走 \n為什麼 人要這麼的脆弱 墮落\n請你打開電視看看\n為生命在努力勇敢的走下去\n還記得你說家是唯一的城堡\n隨著稻香河流繼續(xù)奔跑\n微微笑 小時候的夢我知道"];
    __block CGSize size;
    
       
    [self.label setText:attString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        
        
        NSRange fontRange
        = [[mutableAttributedString string] rangeOfString:@"對這個世界如果你有太多的抱怨"
                                                  options:NSCaseInsensitiveSearch];
        NSRange strokeColorRange1
        = [[mutableAttributedString string] rangeOfString:@"跌倒了 就不敢繼續(xù)往前走"
                                                  options:NSCaseInsensitiveSearch];
        NSRange strikeRange
        = [[mutableAttributedString string] rangeOfString:@"為什麼 人要這麼的脆弱 墮落"
                                                  options:NSCaseInsensitiveSearch];
        NSRange fillColorRange
        = [[mutableAttributedString string] rangeOfString:@"請你打開電視看看"
                                                  options:NSCaseInsensitiveSearch];
        NSRange shadowRange
        = [[mutableAttributedString string] rangeOfString:@"為生命在努力勇敢的走下去"
                                                  options:NSCaseInsensitiveSearch];
        NSRange obliquenessRange
        = [[mutableAttributedString string] rangeOfString:@"還記得你說家是唯一的城堡"
                                                  options:NSCaseInsensitiveSearch];
        
        
        UIEdgeInsets fillPadding  = UIEdgeInsetsMake(0, 0, 0, 0);
        // Core Text APIs use C functions without a direct bridge to UIFont.
        // See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
        UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:16];
        CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
        if (font) {
            
            {
                //字體
                [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName
                                                value:(__bridge id)font
                                                range:fontRange];
                //文字顏色
                [mutableAttributedString addAttribute:(NSString *)kCTForegroundColorAttributeName
                                                value:[UIColor redColor]
                                                range:fontRange];
                CFRelease(font);
            }
            {
                //NSStrokeColorAttributeName設置文字描邊顏色牺六,
                //需要和NSStrokeWidthAttributeName設置描邊寬度,這樣就能使文字空心
                //文字描邊顏色
                [mutableAttributedString addAttribute:NSStrokeColorAttributeName
                                                value:[UIColor blueColor]
                                                range:strokeColorRange1];
                //文字描邊寬度
                [mutableAttributedString addAttribute:NSStrokeWidthAttributeName
                                                value:@(2.0)
                                                range:strokeColorRange1];
            }
            {
                //刪除樣式
                [mutableAttributedString addAttribute:kTTTStrikeOutAttributeName
                                                value:@YES
                                                range:strikeRange];
                
                //加上下劃線
                [mutableAttributedString addAttribute:NSUnderlineStyleAttributeName
                                                value:[NSNumber numberWithInt:3]
                                                range:strikeRange];
                [mutableAttributedString addAttribute:NSUnderlineColorAttributeName
                                                value:[UIColor greenColor]
                                                range:strikeRange];
            }
            {
                //背景色
                [mutableAttributedString addAttribute:kTTTBackgroundFillColorAttributeName
                                                value:[UIColor purpleColor]
                                                range:fillColorRange];
                //控制背景色范圍
                [mutableAttributedString addAttribute:kTTTBackgroundFillPaddingAttributeName
                                                value:[NSNumber valueWithUIEdgeInsets:fillPadding]
                                                range:fillColorRange];
                //控制背景色(文字邊框)的圓角
                [mutableAttributedString addAttribute:kTTTBackgroundCornerRadiusAttributeName
                                                value:@(4)
                                                range:fillColorRange];
                
                //文字邊框顏色
                [mutableAttributedString addAttribute:kTTTBackgroundStrokeColorAttributeName
                                                value:[UIColor purpleColor]
                                                range:fillColorRange];
            }
            {
                //無效
                NSShadow *shadow = [[NSShadow alloc] init];
                [shadow setShadowColor:[UIColor redColor]];
                [shadow setShadowBlurRadius:4.0];
                [shadow setShadowOffset:CGSizeMake(2, 2)];
                //陰影
                [mutableAttributedString addAttribute:NSShadowAttributeName
                                                value:shadow
                                                range:shadowRange];
            }
            {
                //無效
                //斜體
                //NSObliquenessAttributeName 設置字體傾斜度汗捡,取值為 NSNumber(float)淑际,正值右傾,負值左傾
                [mutableAttributedString addAttribute:NSObliquenessAttributeName
                                                value:@(5.0)
                                                range:obliquenessRange];
            }
        }
        //高度計算
        size = [TTTAttributedLabel sizeThatFitsAttributedString:mutableAttributedString
                                                withConstraints:CGSizeMake(kScreenWidth, CGFLOAT_MAX)
                                         limitedToNumberOfLines:0];
        return mutableAttributedString;
        
        
    }];
    
    
    NSRange boldRange1 = [attString.string rangeOfString:@"隨著稻香河流繼續(xù)奔跑" options:NSCaseInsensitiveSearch];
    [self.label addLinkToURL:[NSURL URLWithString:@"http://y.qq.com/portal/song/003aAYrm3GE0Ac.html"]
                    withRange:boldRange1];
    NSRange addressRange = [attString.string rangeOfString:@"微微笑 小時候的夢我知道" options:NSCaseInsensitiveSearch];
    [self.label addLinkToAddress:@{@"detailAdd":@"幸福街122號",
                                   @"lontitude":@"110.011111",
                                   @"latitude":@"30.1234"}
                        withRange:addressRange];
    
    //電話號碼可以自動識別扇住,也可以這樣添加
    //NSRange phoneRange = [text rangeOfString:phoneNum options:NSCaseInsensitiveSearch];
    //[self.label addLinkToPhoneNumber:phoneNum withRange:phoneRange];
    
    self.label.frame = CGRectMake(0, 100, kScreenWidth, size.height);
    [self.view addSubview:self.label];

TTTAttributedLabel 的懶加載

  if (!_label) {
        _label = [[TTTAttributedLabel alloc]initWithFrame:CGRectZero];
        
        _label.lineBreakMode = NSLineBreakByTruncatingHead;
        _label.numberOfLines = 0;
        _label.delegate = self;
        _label.lineSpacing = 10;
        
        /*
         要放在`text`,
         `setText:`
         `setText:afterInheritingLabelAttributesAndConfiguringWithBlock:前面才有效
         */
        
        _label.enabledTextCheckingTypes = NSTextCheckingTypePhoneNumber|
                                          NSTextCheckingTypeAddress|
                                          NSTextCheckingTypeLink;
        //鏈接正常狀態(tài)文本屬性
        _label.linkAttributes = @{
                                   NSForegroundColorAttributeName:[UIColor purpleColor],
                                   NSUnderlineStyleAttributeName:@(1)
                                    };
        //鏈接高亮狀態(tài)文本屬性
        _label.activeLinkAttributes = @{
                                        NSForegroundColorAttributeName:[UIColor redColor],
                                        NSUnderlineStyleAttributeName:@(1)
                                        };
        
    }
    return _label;

TTTAttributedLabel 是代理方法實現(xiàn)所有點擊回調

#pragma mark - TTTAttributedLabelDelegate
//點擊鏈接
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithURL:(NSURL *)url{
    NSLog(@"linkClick");
    [[UIApplication sharedApplication] openURL:url];
}
//點擊地址鏈接
- (void)attributedLabel:(TTTAttributedLabel *)label didSelectLinkWithAddress:(NSDictionary *)addressComponents{
    NSLog(@"addressClick");
    NSLog(@"detailAdd:%@,lontitude:%f,latitude:%f",
          addressComponents[@"detailAdd"],
          [addressComponents[@"lontitude"] floatValue],
          [addressComponents[@"latitude"] floatValue]);
}
//撥的電話
- (void)attributedLabel:(TTTAttributedLabel *)label
didSelectLinkWithPhoneNumber:(NSString *)phoneNumber{
    NSLog(@"phoneClick");
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末春缕,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子艘蹋,更是在濱河造成了極大的恐慌淡溯,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,651評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件簿训,死亡現(xiàn)場離奇詭異咱娶,居然都是意外死亡米间,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,468評論 3 392
  • 文/潘曉璐 我一進店門膘侮,熙熙樓的掌柜王于貴愁眉苦臉地迎上來屈糊,“玉大人,你說我怎么就攤上這事琼了÷呷瘢” “怎么了?”我有些...
    開封第一講書人閱讀 162,931評論 0 353
  • 文/不壞的土叔 我叫張陵雕薪,是天一觀的道長昧诱。 經常有香客問我,道長所袁,這世上最難降的妖魔是什么盏档? 我笑而不...
    開封第一講書人閱讀 58,218評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮燥爷,結果婚禮上蜈亩,老公的妹妹穿的比我還像新娘。我一直安慰自己前翎,他們只是感情好稚配,可當我...
    茶點故事閱讀 67,234評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著港华,像睡著了一般道川。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上立宜,一...
    開封第一講書人閱讀 51,198評論 1 299
  • 那天愤惰,我揣著相機與錄音,去河邊找鬼赘理。 笑死宦言,一個胖子當著我的面吹牛,可吹牛的內容都是我干的商模。 我是一名探鬼主播奠旺,決...
    沈念sama閱讀 40,084評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼施流!你這毒婦竟也來了响疚?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 38,926評論 0 274
  • 序言:老撾萬榮一對情侶失蹤瞪醋,失蹤者是張志新(化名)和其女友劉穎忿晕,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體银受,經...
    沈念sama閱讀 45,341評論 1 311
  • 正文 獨居荒郊野嶺守林人離奇死亡践盼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,563評論 2 333
  • 正文 我和宋清朗相戀三年鸦采,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片咕幻。...
    茶點故事閱讀 39,731評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡渔伯,死狀恐怖,靈堂內的尸體忽然破棺而出肄程,到底是詐尸還是另有隱情锣吼,我是刑警寧澤,帶...
    沈念sama閱讀 35,430評論 5 343
  • 正文 年R本政府宣布玄叠,位于F島的核電站,受9級特大地震影響拓提,放射性物質發(fā)生泄漏读恃。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,036評論 3 326
  • 文/蒙蒙 一崎苗、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧舀寓,春花似錦胆数、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,676評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至篡撵,卻和暖如春判莉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背育谬。 一陣腳步聲響...
    開封第一講書人閱讀 32,829評論 1 269
  • 我被黑心中介騙來泰國打工券盅, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人膛檀。 一個月前我還...
    沈念sama閱讀 47,743評論 2 368
  • 正文 我出身青樓锰镀,卻偏偏與公主長得像,于是被迫代替她去往敵國和親咖刃。 傳聞我的和親對象是個殘疾皇子泳炉,可洞房花燭夜當晚...
    茶點故事閱讀 44,629評論 2 354

推薦閱讀更多精彩內容

  • 發(fā)現(xiàn) 關注 消息 iOS 第三方庫、插件嚎杨、知名博客總結 作者大灰狼的小綿羊哥哥關注 2017.06.26 09:4...
    肇東周閱讀 12,094評論 4 62
  • 如果時光可以倒流 那天花鹅,陽光正好,微風輕拂 虞美人燦爛的招搖 你站在春天里 傾聽 著花開的聲音 我一定踏著晨光 不...
    又見依依閱讀 225評論 0 6
  • 1.過去沒變之景,現(xiàn)在也沒變 在新媒體營銷火爆之前斤富,很多品牌營銷人都在去強調眼球經濟,并努力將自己的品牌與最具有視覺沖...
    姜甘霖閱讀 4,359評論 0 2
  • 不知道什么緣故锻狗,最近接觸的東西好像都巧合般地跟女生的友誼有關满力。先是韓國電影《我們的世界》,說的是小學四年級的兩個小...
    小主正紅閱讀 726評論 6 5