代码之家  ›  专栏  ›  技术社区  ›  pankaj

两种不同颜色文本的UILabel

  •  6
  • pankaj  · 技术社区  · 14 年前

    我怎么能有一个 UILabel 字体有两种颜色?我有两个不同的字符串,我想把第一个字符串作为 红色 其次是 绿色

    5 回复  |  直到 7 年前
        1
  •  7
  •   KingofBliss    11 年前

    你不能在 UILabel s、 但我的建议是 UILabel公司 集中精力 NSAttributedString UIControllers 吸引人的 NSAttributedString UILabel公司 , UITextView 不支持 NSAttributedString .

        2
  •  8
  •   mattt    12 年前

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


    编辑:或者,如果你不想依赖第三方,并且目标是iOS 6, UILabel 现在有了 attributedText 财产。

        3
  •  4
  •   Eiko    14 年前

    UILabel只能有 [yourLabel sizeToFit]; 并相应地放置它们。

        4
  •  1
  •   Krunal    7 年前


    ( 注意: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)
    


    斯威夫特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

        5
  •  0
  •   Mann    11 年前

    在iOS 6中,UILabel具有NSAttributedString属性。所以用这个。