一直對這個類的用法有點糊塗,今天抽了一個時間研究了一下
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.展示出來如圖