ios - 带有两种不同颜色文本的 UILabel

标签 ios objective-c swift uilabel textcolor

我想在 UILabel 中显示这样的字符串:

There are 5 results.

其中数字 5 为红色,字符串的其余部分为黑色。

如何在代码中做到这一点?

最佳答案

这样做的方法是像这样使用 NSAttributedString:

NSMutableAttributedString *text = 
 [[NSMutableAttributedString alloc] 
   initWithAttributedString: label.attributedText];

[text addAttribute:NSForegroundColorAttributeName 
             value:[UIColor redColor] 
             range:NSMakeRange(10, 1)];
[label setAttributedText: text];

我创建了一个 UILabel extension to do it .

关于ios - 带有两种不同颜色文本的 UILabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6501808/

相关文章:

ios - 按比例填充 UIStackView?

objective-c - 禁止转换 NSString

ios - 如何使 firebase 推送通知工作

iOS 9 和 iOS 10 CoreData 同时运行

ios - Nib 中的 IBOutlets 在 awakeFromNib 和 initWithCoder 上都是 nil——没有 subview

objective-c - MTLCreateSystemDefaultDevice 的引用计数返回值

objective-c - 保留 NSArray 中的元素

ios - 当前Facebook SDK中未找到FBLoginView和FBSession

ios - FaSTLane:无法使用 "match"命令生成的 p12 文件

ios - 自定义 UIButton 触发 IBAction 一次,然后再也不会