iOS 富文本(NSMutableAttributedString)详解

来源:互联网 发布:淘宝转化率提升 编辑:程序博客网 时间:2024/05/17 23:27

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

- (instancetype)initWithString:(NSString *)str;- (instancetype)initWithString:(NSString *)str attributes:(nullable NSDictionary<NSString *, id> *)attrs;

初始化的方法和NSMutableString一样。

包含的几个基本方法:

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;//为某一范围内文字添加某个属性- (void)addAttributes:(NSDictionary<NSString *, id> *)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];

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

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

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

0 0
原创粉丝点击