美文网首页
iOS----NSMutableAttributedString

iOS----NSMutableAttributedString

作者: 彬至睢阳 | 来源:发表于2017-09-23 08:36 被阅读0次

在iOS开发中,会有一些需求要求文字显示不同的颜色和字体,也可能会要求给文字或者文字中的某几个加删除线或者下划线的需求。面对这样的需求,当初很抓狂的,但是当了解到NSMutableAttributedString,一个带属性的字符串,上面的问题就很方便的解决了

//使用方法:

UILabel* lab = [[UILabel alloc]init];

[self.view addSubview:lab];

lab.frame = CGRectMake(0, 80, ScreenWidth, 90);

//1.初始化--字符串

NSMutableAttributedString* attStr = [[NSMutableAttributedString alloc]initWithString:@"今天是个好日子"];

//存放属性名和属性值的字典

NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:

[UIFont systemFontOfSize:15.0],NSFontAttributeName,

[UIColor redColor],NSForegroundColorAttributeName,

NSUnderlineStyleAttributeName,NSUnderlineStyleSingle,nil];

[attStr setAttributes:attributeDict range:NSMakeRange(0, attStr.length)];

lab.attributedText = attStr;

使用方法:

为某一范围内文字设置多个属性

- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;

为某一范围内文字添加某个属性

- (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range;

为某一范围内文字添加多个属性

- (void)addAttributes:(NSDictionary *)attrs range:(NSRange)range;

移除某范围内的某个属性

- (void)removeAttribute:(NSString *)name range:(NSRange)range;

2.    常见的属性及说明

NSFontAttributeName

字体

NSParagraphStyleAttributeName

段落格式

NSForegroundColorAttributeName

字体颜色

NSBackgroundColorAttributeName

背景颜色

NSStrikethroughStyleAttributeName

删除线格式

NSUnderlineStyleAttributeName

下划线格式

NSStrokeColorAttributeName

删除线颜色

NSStrokeWidthAttributeName

删除线宽度

NSShadowAttributeName

阴影

但是在iOS10.3系统以后--删除 删除线(NSStrikethroughStyleAttributeName)富文本不显示,确切的说是在字符串中间某一段文字添加删除线富文本会出现异常。给整个字符串添加删除线富文本也不行。只要是添加删除线富文本的字符串中包含中文就是不行;

另外在iOS10.3以后,这个人民币符号“¥”和“¥”的区别,前面那个就可以,后面直接切换成中文输入法的就不行。

iOS 10.3上显示异常,需要在添加一个NSBaselineOffsetAttributeName属性才可以。

如 [attStr addAttribute:NSBaselineOffsetAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(0, 3)];

注意:这个时候在模拟器上是可以的,真机上还是不行。原因就是你设置字符串中的某一段文字下划线富文本。

直接给某一字符串全体设置下划线富文本是可以的

相关文章

  • iOS----NSMutableAttributedString

    在iOS开发中,会有一些需求要求文字显示不同的颜色和字体,也可能会要求给文字或者文字中的某几个加删除线或者下划线的...

网友评论

      本文标题:iOS----NSMutableAttributedString

      本文链接:https://www.haomeiwen.com/subject/xjsfextx.html