故事板中带有不同颜色文本的 UILabel

UILabel with text of different color in Storyboard

我尝试以编程方式使用不同颜色的文本设置 UILabel,

NSMutableAttributedString * string = [[NSMutableAttributedString alloc] initWithString:@"firstsecondthird"];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,5)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor greenColor] range:NSMakeRange(5,6)];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:NSMakeRange(11,5)];
[self.resultLabel setAttributedText:string];

我得到了我所期望的。但是,我有兴趣在 main.storyboard 的情节提要中做所有这些事情。谁能帮我做这个。


这就是我想要的,

如果我对你的问题的理解正确,那么在情节提要中,大多数选项旁边都有小加号按钮,以便你可以自定义标签和属性。确保您使用的不是纯文本而是属性文本,它是列中的第一个下拉选项。

希望对您有所帮助,如果我理解有误,请告诉我!

要在 storyboard 中实现这一点,请为 label 的文本添加属性,然后 select 范围并相应地更改颜色。

见下图:

希望对您有所帮助。

您需要将文本样式更改为 attributed 然后您可以 select 一些字符并更改它们的颜色。请看图

检查@IBInspectable 和@IBDesignable。为 UILabel 创建子类或扩展。

import UIKit

@IBDesignable class AttributedStringLabel: UILabel {

    @IBInspectable open var firstText: String = ""

    @IBInspectable open var firstColor: UIColor?
    @IBInspectable open var secondColor: UIColor?
    @IBInspectable open var thirdColor: UIColor?


    override func awakeFromNib() {
        super.awakeFromNib()

        let attrString :NSMutableAttributedString  = NSAttributedString([![string][1]][1]: firstText) as! NSMutableAttributedString

        attrString.addAttribute(NSForegroundColorAttributeName, value: firstColor! as UIColor, range: NSMakeRange(0, 5))
        attrString.addAttribute(NSForegroundColorAttributeName, value: secondColor! as UIColor, range: NSMakeRange(5, 6))
        attrString.addAttribute(NSForegroundColorAttributeName, value: thirdColor! as UIColor, range: NSMakeRange(11, 15))
        self.attributedText = attrString

    }


}

下面是截图,您可以根据需要自定义代码,您可以添加任何您想要的Range作为IBInspectable变量。

使用故事板界面:

与 Swift 3 & 4
您可以通过编程非常轻松地设置标签颜色。

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 setColoredLabel() {
        var string: NSMutableAttributedString = NSMutableAttributedString(string: "My label with red blue and green colored text")
        string.setColorForText(textToFind: "red", withColor: UIColor.red)
        string.setColorForText(textToFind: "blue", withColor: UIColor.blue)
        string.setColorForText(textToFind: "green", withColor: UIColor.green)
        yourLabel.attributedText = string
    }

结果: