Use multiple font colors in a single label

Justin Rose picture Justin Rose · Jan 1, 2015 · Viewed 97.1k times · Source

Is there a way to use two, or even three font colors in a single label in iOS?

If the text "hello, how are you" were used as an example, the "hello," would be blue, and the "how are you" would be green?

Is this possible, it seems easier than creating multiple labels?

Answer

Kirit Modi picture Kirit Modi · Jan 1, 2015

Reference from here.

First of all initialize of you NSString and NSMutableAttributedString as below.

var myString:NSString = "I AM KIRIT MODI"
var myMutableString = NSMutableAttributedString()

In ViewDidLoad

override func viewDidLoad() {

    myMutableString = NSMutableAttributedString(string: myString, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 18.0)!])
    myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: NSRange(location:2,length:4))
    // set label Attribute
    labName.attributedText = myMutableString
    super.viewDidLoad()
}

OUTPUT

enter image description here

MULTIPLE COLOR

Add the line code below in your ViewDidLoad to get multiple colors in a string.

 myMutableString.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location:10,length:5))

Multiple color OUTPUT

enter image description here

Swift 4

var myMutableString = NSMutableAttributedString(string: str, attributes: [NSAttributedStringKey.font :UIFont(name: "Georgia", size: 18.0)!])
myMutableString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRange(location:2,length:4))