UILabel在Storyboard中使用不同颜色的文本

For*_*Zhu 7 xcode objective-c textcolor uilabel ios

我尝试用编程方式使用不同颜色的文本设置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];
Run Code Online (Sandbox Code Playgroud)

我得到了我的预期.但是,我有兴趣在story.storyboard中的storyboard中完成所有这些工作.任何人都可以帮我这样做.


这就是我要的,

在此输入图像描述

iPe*_*ter 14

要实现这一点storyboard,请将label文本归结为,然后选择范围并相应地更改颜色.

见下图:

在此输入图像描述

希望这可以帮助.


Ser*_*gey 12

您需要更改文本样式归因那么你可以选择一些人物和改变它们的颜色.请看图像

http://take.ms/kq36u


Kru*_*nal 8

使用故事板界面:

在此输入图像描述

使用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
    }
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述