6

我怎样才能有UILabel两种不同颜色的字体?我将在两个不同的字符串中有文本,我想将第一个字符串作为red和第二个作为green的文本。两个字符串的长度都是可变的。

4

5 回答 5

8

试试TTTAttributedLabel。它是支持NSAttributedStrings 的 UILabel 的子类,这使得在同一个字符串中拥有多种颜色、字体和样式变得容易。


编辑:或者,如果您不想要第 3 方依赖并且针对 iOS 6,UILabel现在拥有该attributedText属性。

于 2011-05-09T19:21:01.027 回答
7

您不能在UILabels 内执行此操作。但我的建议是,不要使用多个,UILabel而是专注于NSAttributedString. 找UIControllers那个抽奖NSAttributedString因为UILabelUITextView不支持NSAttributedString

PS:如果你打算发布 iOS6 或更高版本的应用程序,由于 UILabel 现在支持 NSAttributedString,你应该直接使用 UILabel 而不是 OHAttributedLabel,因为它现在已经被操作系统原生支持。

于 2010-11-15T11:04:22.700 回答
4

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

于 2010-10-17T08:44:58.153 回答
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
    }

结果:

在此处输入图像描述

于 2017-07-06T16:51:17.050 回答
0

在 iOS 6 UILabel 有 NSAttributedString 属性。所以用那个。

于 2013-06-26T09:05:13.030 回答