富文本处理

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");
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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