UILabel有两种不同颜色的文字

时间:2010-10-17 08:40:34

标签: ios xcode uilabel nsattributedstring textcolor

如何为字体设置两种不同颜色的UILabel?我将在两个不同的字符串中包含文本,我希望将第一个字符串的文本设为红色,其次为绿色。字符串的长度都是可变的。

5 个答案:

答案 0 :(得分:8)

试试TTTAttributedLabel。它是UILabel的一个子类,支持NSAttributedString,这样可以很容易地在同一个字符串中包含多种颜色,字体和样式。


编辑:或者,如果您不想要第三方依赖关系并且定位到iOS 6,则UILabel现在具有attributedText属性。

答案 1 :(得分:7)

您无法在UILabel内执行此操作。但我的建议是,不要使用多个UILabel而只关注NSAttributedString。查看提取UIControllers的{​​{1}},因为NSAttributedStringUILabel不支持UITextView

PS:如果您计划分发iOS6或更高版本的应用程序,因为UILabel现在支持NSAttributedString,您应该直接使用UILabel而不是OHAttributedLabel,因为它现在可以由OS本机支持。

答案 2 :(得分:4)

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

答案 3 :(得分:1)

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
    }

<强>结果:

enter image description here

答案 4 :(得分:0)

在iOS 6中,UILabel具有NSAttributedString属性。所以使用它。

相关问题