富文本处理

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跌倒了 就不敢继续往前走 \n为什麼 人要这麼的脆弱 堕落\n请你打开电视看看\n为生命在努力勇敢的走下去\n还记得你说家是唯一的城堡\n随著稻香河流继续奔跑\n微微笑 小时候的梦我知道"];
    __block CGSize size;
    
       
    [self.label setText:attString afterInheritingLabelAttributesAndConfiguringWithBlock:^NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
        
        
        NSRange fontRange
        = [[mutableAttributedString string] rangeOfString:@"对这个世界如果你有太多的抱怨"
                                                  options:NSCaseInsensitiveSearch];
        NSRange strokeColorRange1
        = [[mutableAttributedString string] rangeOfString:@"跌倒了 就不敢继续往前走"
                                                  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:@"随著稻香河流继续奔跑" 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;
        //链接正常状态文本属性
        _label.linkAttributes = @{
                                   NSForegroundColorAttributeName:[UIColor purpleColor],
                                   NSUnderlineStyleAttributeName:@(1)
                                    };
        //链接高亮状态文本属性
        _label.activeLinkAttributes = @{
                                        NSForegroundColorAttributeName:[UIColor redColor],
                                        NSUnderlineStyleAttributeName:@(1)
                                        };
        
    }
    return _label;

TTTAttributedLabel 是代理方法实现所有点击回调

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

推荐阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,979评论 4 60
  • 如果时光可以倒流 那天,阳光正好,微风轻拂 虞美人灿烂的招摇 你站在春天里 倾听 着花开的声音 我一定踏着晨光 不...
    又见依依阅读 220评论 0 6
  • 1.过去没变,现在也没变 在新媒体营销火爆之前,很多品牌营销人都在去强调眼球经济,并努力将自己的品牌与最具有视觉冲...
    姜甘霖阅读 4,311评论 0 2
  • 不知道什么缘故,最近接触的东西好像都巧合般地跟女生的友谊有关。先是韩国电影《我们的世界》,说的是小学四年级的两个小...
    小主正红阅读 706评论 6 5