开发中,常常会有一段文字显示不同的颜色和字体,或者给某几个文字加删除线或下划线的需求。NSMuttableAttstring(带属性的字符串),上面的一些需求都可以很简便的实现。
1.实例化方法有两种:
使用字符串来初始化
①:- (id)initWithString:(NSString *)str;
例如:
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"满1000减60的优惠券一张"];
②初始化的同时,将其属性也进行改变
- (id)initWithString:(NSString *)str attributes:(NSDictionary *)attrs;
例子:
NSDictionary *attributeDict = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:15.0],NSFontAttributeName,
[UIColor redColor],NSForegroundColorAttributeName,nil];
NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"满1000减60的优惠券一张" attributes:attributeDict];
使用方法①进行初始化时,初始化完后要再利用相关的方法进行属性的设置,常使用的方法如下:
为某一范围内文字设置多个属性
- (void)setAttributes:(NSDictionary *)attrs range:(NSRange)range;
为某一范围内文字添加某个属性
- (void)addAttribute:(NSString *)