在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)];
注意:這個時候在模擬器上是可以的,真機上還是不行。原因就是你設置字符串中的某一段文字下劃線富文本。
直接給某一字符串全體設置下劃線富文本是可以的