UILabel有两种不同颜色的文字

我怎样才能有两种不同颜色的字体UILabel ? 我将有两个不同的string文本,我想使第一个string为红色 ,第二个为绿色的文本。 这两个string的长度是可变的。

你不能在UILabel做这个。 但我的build议是,而不是使用多个UILabel只是集中在NSAttributedString 。 查找绘制NSAttributedString UIControllers ,因为UILabelUITextView不支持NSAttributedString

PS:如果你打算分发一个iOS6或更高版本的应用程序,因为UILabel现在支持NSAttributedString,所以你应该直接使用UILabel而不是OHAttributedLabel,因为它现在被操作系统本身支持。

试试TTTAttributedLabel 。 它是UILabel的一个子类,它支持NSAttributedString ,这可以使得在同一个string中有多种颜色,字体和样式。


编辑:或者,如果你不想第三方依赖项,并针对iOS 6, UILabel现在具有的attributedText UILabel属性。

UILabel只能有一种颜色。 您可能需要更复杂的元素,或者 – 可能更简单 – 只需使用两个单独的标签。 使用[yourLabel sizeToFit]; 并相应地放置它们。

在iOS 6中,UILabel具有NSAttributedString属性。 那就用那个吧

斯威夫特4
注意:归因于string键的符号在swift 4中被改变

这里是NSMutableAttributedString的扩展,它在string/文本上添加/设置颜色。

 extension NSMutableAttributedString { func setColor(color: UIColor, forText stringValue: String) { let range: NSRange = self.mutableString.range(of: stringValue, options: .caseInsensitive) self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range) } } 

现在,使用UILabel尝试以上扩展名并查看结果

 let label = UILabel() label.frame = CGRect(x: 40, y: 100, width: 280, height: 200) let red = "red" let blue = "blue" let green = "green" let stringValue = "\(red)\n\(blue)\n&\n\(green)" label.textColor = UIColor.lightGray label.numberOfLines = 0 let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue) attributedString.setColor(color: UIColor.red, forText: red) // or use direct value for text "red" attributedString.setColor(color: UIColor.blue, forText: blue) // or use direct value for text "blue" attributedString.setColor(color: UIColor.green, forText: green) // or use direct value for text "green" label.font = UIFont.systemFont(ofSize: 26) label.attributedText = attributedString self.view.addSubview(label) 

这里是Swift 3中的解决scheme:

 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 multicolorTextLabel() { var string: NSMutableAttributedString = NSMutableAttributedString(string: "red\nblue\n&\ngreen") string.setColorForText(textToFind: "red", withColor: UIColor.red) string.setColorForText(textToFind: "blue", withColor: UIColor.blue) string.setColorForText(textToFind: "green", withColor: UIColor.green) labelObject.attributedText = string } 

结果:

在这里输入图像说明