标签:
一直对这个类的用法有点糊涂,今天抽了一个时间研究了一下
1.首先来看系统的api(方法)
1 @interface NSMutableAttributedString : NSAttributedString 2 3 - (void)replaceCharactersInRange:(NSRange)range withString:(NSString *)str; 4 - (void)setAttributes:(nullable NSDictionary<NSString *, id> *)attrs range:(NSRange)range; 5 6 @end 7 8 @interface NSMutableAttributedString (NSExtendedMutableAttributedString) 9 10 @property (readonly, retain) NSMutableString *mutableString; 11 12 - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)range; 13 - (void)addAttributes:(NSDictionary<NSString *, id> *)attrs range:(NSRange)range; 14 - (void)removeAttribute:(NSString *)name range:(NSRange)range; 15 16 - (void)replaceCharactersInRange:(NSRange)range withAttributedString:(NSAttributedString *)attrString; 17 - (void)insertAttributedString:(NSAttributedString *)attrString atIndex:(NSUInteger)loc; 18 - (void)appendAttributedString:(NSAttributedString *)attrString; 19 - (void)deleteCharactersInRange:(NSRange)range; 20 - (void)setAttributedString:(NSAttributedString *)attrString; 21 22 - (void)beginEditing; 23 - (void)endEditing;
2.在此呢 基本类 有两个方法3-4 又给这个NSMutableAttributedString添加了一个类别NSExtendedMutableAttributedString。简单介绍几个方法的用法
3.总的来说 共有这几种情况 3.范围替换 4.范围多属性 12.范围单属性 13.范围多属性 14.移除范围单属性 16.范围替换(用NSMutableAttributedString) 等 其他的自己尝试
4.下面是我简单的写了一点代码
1 NSString *string = @"这是一个完整的句子吧"; 2 3 UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 70, 250, 50)]; 4 [self.view addSubview:label]; 5 6 //初始化一个attriburitedString对象 7 _attributeString = [[NSMutableAttributedString alloc] initWithString:string]; 8 9 //给这个属性添加一个属性前3个字符的背景颜色 10 NSRange orRange = NSMakeRange(0, 3); 11 [_attributeString addAttribute:NSBackgroundColorAttributeName value:[UIColor yellowColor] range:orRange]; 12 13 14 //更换string的部分字符串 15 NSRange reRange = NSMakeRange(3, 2); 16 [_attributeString replaceCharactersInRange:reRange withString:@"qinguangyi"]; 17 18 //添加多个属性 19 NSRange seRange = NSMakeRange(8, 5); 20 [_attributeString setAttributes:@{ 21 NSForegroundColorAttributeName: 22 [UIColor redColor], 23 NSBackgroundColorAttributeName: 24 [UIColor blueColor], 25 } range:seRange]; 26 27 NSMutableAttributedString *newAttributeString = [[NSMutableAttributedString alloc] initWithString:@"NEW"]; 28 29 /* 其他属性自己尝试 30 [_attributeString replaceCharactersInRange:NSMakeRange(0, 3) withString:@"123"]; 31 [_attributeString insertAttributedString:newAttributeString atIndex:0]; 32 [_attributeString deleteCharactersInRange:NSMakeRange(0, 3)]; 33 [_attributeString appendAttributedString:newAttributeString]; 34 35 [_attributeString setAttributedString:newAttributeString]; 36 */ 37 38 39 40 //最简单的给label赋值的方法打点调用attributedText 41 label.attributedText = _attributeString;
5.展示出来如图
NSMutableAttributedString的简单用法
标签:
原文地址:http://www.cnblogs.com/guangyi-qin/p/5135225.html