iOS 富文本(NSMutableAttributedString)详解

2,000 阅读1分钟
原文链接: blog.csdn.net

在开发中,相信很多人会遇到在一个label中设置不同字体大小、不同颜色或者加下划线、删除线等问题呢,这里就是用到了NSMutableAttributedString(带属性的字符串)。
首先先了解一下NSMutableAttributedString:
初始化方法:

- (instancetype)initWithString:(NSString *)str;
- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary *)attrs;

初始化的方法和NSMutableString一样。

包含的几个基本方法:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;
- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;
- (void)removeAttribute:(NSString *)name range:(NSRange)range;

常见的属性有:

 NSFontAttributeName  

NSParagraphStyleAttributeName  

NSForegroundColorAttributeName  

NSBackgroundColorAttributeName  

NSStrikethroughStyleAttributeName 

NSUnderlineStyleAttributeName     

NSStrokeColorAttributeName       

NSStrokeWidthAttributeName   

NSShadowAttributeName   

简单例子:

  NSString *string = @"我是一个中国人!";
    
  NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:string];
    [attributedString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.0] range:NSMakeRange(0,4)];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(4, 4)];
    [_label setAttributedText:attributedString];

运行结果:
这里写图片描述

另一个例子:

 NSString *string = @"我是一个中国人!";
    NSDictionary *attributeDict = @{NSFontAttributeName:[UIFont systemFontOfSize:15.0],NSForegroundColorAttributeName:[UIColor redColor],NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle)};
    NSMutableAttributedString *str = [[NSMutableAttributedString alloc]initWithString:string attributes:attributeDict];
    [_label setAttributedText:str];

运行结果:
这里写图片描述

具体效果可以根据需求然后根据以上属性进行设置呢。

以上如有错误,请留言指出谢谢。