NSAttributedString实现富文本

有的时候需要显示的字符串带有不同颜色,字体大小也不同,这时就可以用NSMutableAttributedString来设置字符串。


通过设置Attributed(特性)来改变:

  • NSForegroundColorAttributeName
  • NSFontAttributeName
  • NSStrokeColorAttributeName
  • NSStrokeWidthAttributeName
  • NSShadowAttributeName
  • NSObliquenessAttributeName
  • NSExpansionAttributeName
下面是主要代码:
   NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"请到店出示您的编码[5110001],为了您的账户安全请不要将您的编号随意转告他人,谢谢您的关顾"];
    
    //设置文本颜色
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(1, 4)];
    //设置文本字体大小
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(1, 4)];
    
    //设置文本颜色
    [str addAttribute:NSForegroundColorAttributeName value:[UIColor yellowColor] range:NSMakeRange(10,7)];
    //设置文本字体大小
    [str addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"HelveticaNeue-Bold" size:15.0] range:NSMakeRange(10, 7)];
    
    //stroke
    [str addAttribute:NSStrokeColorAttributeName value:[UIColor lightGrayColor] range:NSMakeRange(5, 3)];
    [str addAttribute:NSStrokeWidthAttributeName value:@(3.0) range:NSMakeRange(5, 3)];
    [str addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:22] range:NSMakeRange(5, 3)];
    
    //加入阴影
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor redColor];
    shadow.shadowOffset = CGSizeMake(0, 0);
    shadow.shadowBlurRadius = 5.0;
    [str addAttribute:NSShadowAttributeName value:shadow range:NSMakeRange(23, 4)];
    
    //扭曲
    [str addAttribute:NSObliquenessAttributeName value:@(1.0) range:NSMakeRange(27, 3)];
    
    //扩大
    [str addAttribute:NSExpansionAttributeName value:@(0.5) range:NSMakeRange(30, 3)];
    
    //设置段落间隔
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:10];
    [str addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [str length])];
    
    label1.attributedText = str;

    label1.numberOfLines = 0;

效果图

NSAttributedString实现富文本_第1张图片

你可能感兴趣的:(NSAttributedString实现富文本)