UILabel* label = [[UILabel alloc] init];
label.frame = CGRectMake(0, 100, 200, 100);
label.textColor = [UIColor blackColor];
NSMutableAttributedString *str = [[NSMutableAttributedString alloc] initWithString:@"1234567890"];
NSRange range = NSMakeRange(0, [[str string] rangeOfString:@"5"].location);
//NSRange range = NSMakeRange(0,6); //这里是设置从第一个字符到第六个字符
[str addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
[label setAttributedText:str] ;
[label sizeToFit];
[self.view addSubview:label];
下面研究下AttributedString究竟可以设置哪些属性,具体来说,有以下21个:
// NSFontAttributeName 设置字体属性,默认值:字体:Helvetica(Neue) 字号:12
// NSForegroundColorAttributeNam 设置字体颜色,取值为 UIColor对象,默认值为黑色
// NSBackgroundColorAttributeName 设置字体所在区域背景颜色&

这篇博客展示了如何使用NSAttributedString来为UILabel设置颜色和字体大小。通过创建NSMutableAttributedString并设置特定范围的颜色,实现了文本中不同部分显示不同颜色的效果。同时,文章详细列举了NSAttributedString可设置的21个属性,包括字体、颜色、背景色、连体字、间距、删除线、下划线、笔画宽度、阴影、基线偏移等,提供了丰富的文本装饰和排版选项。
最低0.47元/天 解锁文章

258

被折叠的 条评论
为什么被折叠?



