具有多种字体颜色的UILabel文本

有没有办法让UILabeltextColor属性是两个不同的UIColors ? 基本上我试图使UILabel text property的第一个字符是greenColor ,其余的是blackColor 。 我想避免使用两个不同的UILabels因为我可能想要改变绿色字符文本中的位置。

UILabel不支持这个属性…

使用应使用NSAttributedString …并使用控制器来绘制NSAttributesString …

控制器为NSAttributedString

更新:

从iOS 6开始,您可以执行以下操作:

 label.attributedText = attributedString; 

从ios 6开始,您可以执行以下操作:

 NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string]; [attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,3)]; [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(4,9)]; cell.label.attributedText = attributedString; 

NSAttributedStrings支持同一string中的混合字体,样式和颜色,但目前不支持任何标准的UIKit控件。 这就是说,你应该检查出TTTAttributedLabel 。 这是一个简单,高性能的UILabel替代品,可以让你真正轻松地显示丰富的文本。

否 – 苹果说,如果你需要格式化文本,你应该在UIWebView使用HTML。 (请参阅UITextView API文档的概述部分的注释。)

另一种方法是用不同的颜色创build多个标签并将它们排列在一起。 尝试使标签的背景颜色透明。 这可能是乏味的,但应该工作。

Swift 3

 extension NSMutableAttributedString { func setColorForText(textToFind: String, withColor color: UIColor) { let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive) if range != nil { self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) } } } func setColoredLabel() { var string: NSMutableAttributedString = NSMutableAttributedString(string: "My label with red blue and green colored text") string.setColorForText(textToFind: "red", withColor: UIColor.red) string.setColorForText(textToFind: "blue", withColor: UIColor.blue) string.setColorForText(textToFind: "green", withColor: UIColor.green) mylabel.attributedText = string } 

结果:

在这里输入图像说明

不,这是不可能的 – 你需要自己画或者用几个标签来组合。

如果你可以接受3.2的兼容性,你可以看看NSAttributedString

目前不可能,通常你会使用一个NSAttributedString,但是在iOS上使用这个,你需要滚动你自己的标签。 你可以使用UIWebView来解决这个问题,但是我不喜欢这样做,这看起来很重要。