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,
Using storyboard interface:
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With