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

我想在 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 .

https://stackoverflow.com/questions/6501808/

相关文章:

ios - 获取 UITableView 的 Selected 索引

iphone - 如何将 UIImage 保存到文件中?

ios - 如何在 xcode 中以编程方式向按钮添加操作

objective-c - 如何从 NSSet 返回 NSMutableArray

ios - 如何在 UITextView 中禁用复制、剪切、选择、全选

ios - AVAudioPlayer 在 Debug模式下抛出断点

ios - UILabel minimumScaleFactor 是如何工作的?

ios - 错误 : CUICatalog: Invalid asset name supplied

objective-c - 如何获取 NSString 的前三个字符?

iphone - 我什么时候应该在 -(void)viewDidUnload 而不是 -deallo