Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UILabel with text of different color in Storyboard

I try to set UILabel with text of different colors programmatically using,

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];

I get what I expected. But, I am interested in doing all these stuff in storyboard,in main.storyboard. Can anyone help me in doing this.


This is what I want,

enter image description here

like image 346
Forte Zhu Avatar asked Feb 14 '17 10:02

Forte Zhu


1 Answers

Using storyboard interface:

enter image description here

with Swift 3 & 4:
Programatically you can set label colors very easily.

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
    }

Result:

enter image description here

like image 112
Krunal Avatar answered Oct 16 '22 02:10

Krunal