NSMutableAttributedString初探

来源:互联网 发布:淘宝男士鞋 编辑:程序博客网 时间:2024/04/25 21:27
NSMutableAttributedString 指具有多属性字符串。

如:字符串中有不同颜色的字。

NSString *string = @"我的名字叫kendami啊";NSMutableAttributedString *aString = [[NSMutableAttributedString alloc]initWithString:string];[aString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:[string rangeOfString:@"kendami"]];[self.label setAttributedText:aString];
其中关键字是:NSForegroundColorAttributeName
效果如图1

图1

字符串中有不同字体
只需要增加一行代码
[aString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:12] range:[string rangeOfString:@"kendami"]];
关键字:NSFontAttributeName:字体
效果如图2

图2

设置行间距
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];[paragraphStyle setLineSpacing:10.0f];//每行间距10[aString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [string length])];self.label.numberOfLines = 0;
关键字:NSParagraphStyleAttributeName
设置前如图3所示,设置后如图4所示

图3

图4

NSMutableAttributedString还包括很多其他属性,具体可查看UIKIT下NSAttributedString.h头文件。
*需要注意的是,给UILabel设置内容时,需使用setAttributedText函数。
0 0
原创粉丝点击