我怎样才能有UILabel
两种不同颜色的字体?我将在两个不同的字符串中有文本,我想将第一个字符串作为red和第二个作为green的文本。两个字符串的长度都是可变的。
5 回答
试试TTTAttributedLabel。它是支持NSAttributedString
s 的 UILabel 的子类,这使得在同一个字符串中拥有多种颜色、字体和样式变得容易。
编辑:或者,如果您不想要第 3 方依赖并且针对 iOS 6,UILabel
现在拥有该attributedText
属性。
您不能在UILabel
s 内执行此操作。但我的建议是,不要使用多个,UILabel
而是专注于NSAttributedString
. 找UIControllers
那个抽奖NSAttributedString
因为UILabel
,UITextView
不支持NSAttributedString
。
PS:如果你打算发布 iOS6 或更高版本的应用程序,由于 UILabel 现在支持 NSAttributedString,你应该直接使用 UILabel 而不是 OHAttributedLabel,因为它现在已经被操作系统原生支持。
UILabel 只能有一种颜色。您要么需要更复杂的元素,要么 - 可能更简单 - 只需使用两个单独的标签。相应地使用[yourLabel sizeToFit];
和放置它们。
Swift 4
(注意:属性字符串键的符号在 swift 4 中更改)
这是 的扩展NSMutableAttributedString
,在字符串/文本上添加/设置颜色。
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中的解决方案:
extension NSMutableAttributedString {
func setColorForText(textToFind: String, withColor color: UIColor) {
let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
if range != nil {
self.addAttribute(NSForegroundColorAttributeName, 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
}
结果:
在 iOS 6 UILabel 有 NSAttributedString 属性。所以用那个。