Is there a way to have the textColor
property of a UILabel
be two different UIColors
? Basically I\'m trying to make the first characte
not currently possible, usually you would use an NSAttributedString, but to use this on iOS you would need to roll your own label. you may be able to work round this using a UIWebView, but I don't like to do that, it seems heavy handed.
UILabel doesnot supprt this property...
Use should use NSAttributedString... and use controllers for drawing NSAttributesString...
Controller for NSAttributedString
UPDATE:
From iOS 6 you can do the following :
label.attributedText = attributedString;
No, that's not possible - you need to draw on your own or compose using several labels.
If you can accept 3.2 compatibility, you might have a look at NSAttributedString
.
No - Apple say you should use HTML in a UIWebView
if you need formatted text. (See the note in the overview section of the UITextView API docs.)
Starting from ios 6 you can do the following :
NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:string];
[attributedString addAttribute:NSBackgroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(0,3)];
[attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(4,9)];
cell.label.attributedText = attributedString;
Swift 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(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)
mylabel.attributedText = string
}
Result: