Eyal
Eyal

Reputation: 10828

Objective c - Multiple colors in a label

What is the easiest way to have a label with different colors?

For example I want to present the message:
"John Johnson sent you a message"

But I want that John Johnson will be in blue color
and the rest of the message in black color.

Upvotes: 3

Views: 3713

Answers (6)

Krunal
Krunal

Reputation: 79776

Try this with swift (execute code with following extension)

extension NSMutableAttributedString {

    func setColorForText(textToFind: String, withColor color: UIColor) {
        let range: NSRange = self.mutableString.range(of: textToFind, options: .caseInsensitive)
        self.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: range)
    }

}

Try an extension with UILabel:

let label = UILabel()
label.frame = CGRect(x: 40, y: 100, width: 280, height: 200)
let stringValue = "John Johnson sent you a message"  // or direct assign single string value like "firstsecondthird"
label.textColor = UIColor.lightGray
label.numberOfLines = 0
let attributedString: NSMutableAttributedString = NSMutableAttributedString(string: stringValue)
attributedString.setColorForText(textToFind: "John Johnson", withColor: UIColor.blue)
label.font = UIFont.systemFont(ofSize: 26)
label.attributedText = attributedString
self.view.addSubview(label)

Here is result:

enter image description here

Upvotes: 0

João Costa
João Costa

Reputation: 2355

I created an UILabel extension to do this. Basically what it does is use NSAttributedString to define the color for some particular range: https://github.com/joaoffcosta/UILabel-FormattedText

If you wish to implement this behavior yourself, just do the following:

NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithAttributedString: @"John Johnson sent you a message"];
[text addAttribute: NSFontAttributeName
             value: font
             range: range];
[self setAttributedText: text];

Upvotes: 0

Mathew Varghese
Mathew Varghese

Reputation: 4527

Use CoreText. Hope this helps.

Upvotes: 1

bitmapdata.com
bitmapdata.com

Reputation: 9600

In UILabel basically impossible. If you want to this you must override drawTextInRect should be executed. But I will recommend OHAttributedLabel. this is have a attributedString is a textcolor can be set to specify a range.

Upvotes: 3

graver
graver

Reputation: 15213

You need the NSAttributedString class (or the mutable one - NSMutableAttributedString) in order to set attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string and a custom label control that can visualize NSAttributedString like TTTAttributedLabel.

Upvotes: 4

Mundi
Mundi

Reputation: 80271

Use a UIWebView.

webView.text = 
  @"<span style:\"color:blue;\">John Johnson</span> sent you a message.";

Upvotes: 2

Related Questions