Search code examples
swiftcolorslabelswift3nsmutableattributedstring

How to change colour of the certain words in label - Swift 3


Created a Label with a simple text.

How can I change the color of the certain words in the label?

Swift 3

Like below-

Expected result


Solution

  • Use NSMutableAttributedString to apply colors for different words in a string. Try this, there are already lot of similar questions have the answers in SO.

    let myLabel = UILabel()
    var stringOne = "Swift 3 has come"
    let stringTwo = "has"
    
    let range = (stringOne as NSString).range(of: stringTwo)
    
    let attributedText = NSMutableAttributedString.init(string: stringOne)
    attributedText.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue , range: range)
    myLabel.attributedText = attributedText