iOS开发 ☞ NSMutableAttributedString详解

来源:互联网 发布:windows store是什么 编辑:程序博客网 时间:2024/05/02 04:22

原文链接地址:http://blog.csdn.net/magicZYJ/article/details/51068578
一、常用方法:
为某一范围内文字设置多个属性
setAttributes: range:
为某一范围内文字添加某个属性
addAttribute: value: range:
为某一范围内文字添加多个属性
addAttributes: range:
移除某范围内的某个属性
removeAttribute: range:

二、常见的属性及说明
字体
NSFontAttributeName
段落格式
NSParagraphStyleAttributeName

//(From stack Overflow)NSMutableAttributedString* attrString = [NSMutableAttributedString attributedStringWithString:@"Sample text"];NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];[style setLineSpacing:24];[attrString addAttribute:NSParagraphStyleAttributeName    value:style    range:NSMakeRange(0, strLength)];uiLabel.attributedText = attrString;

字体颜色
NSForegroundColorAttributeName
背景颜色
NSBackgroundColorAttributeName
删除线格式
NSStrikethroughStyleAttributeName
下划线格式
NSUnderlineStyleAttributeName
删除线颜色
NSStrokeColorAttributeName
删除线宽度
NSStrokeWidthAttributeName
阴影
NSShadowAttributeName

三、使用误区
来看一个使用NSMutableAttributeString最常见的Bug

-[NSConcreteAttributedString setAttributes:range:]: unrecognized selector sent to instance 0x7fbc8bded2c0

四、局限性
当我们使用NSMutableAttributedString作为属性时 ,不可以用copy,应当用strong,原因如下:
当我们使用copy时
@property (nonatomic,copy)NSMutableAttributedString *a
在我们使用这个属性时执行set方法时会进行copy之后再赋值,而copy出来的都是不可变的所以不能在使用可变方法,如果使用Strong,在set方法是直接赋值,不执行copy操作,所以当用可变的值为其赋值后,可以在使用可变的方法,所以我们在使用可变属性时采用strong。

如果我们设置了Button的attributeString属性,如果想要覆盖,只能重新设置这个属性

设置Label.AttributeText属性时 Label的numberoflines属性是无效的,必须同时给足label的高度,才可以折行显示。

1 0