4

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

Vikrant
  • 4,920
  • 17
  • 48
  • 72
Eugene Or
  • 53
  • 1
  • 6

1 Answers1

12

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
Santosh
  • 2,900
  • 1
  • 16
  • 16
  • Thanks, good decision! But this way we can change the color only of the one word in our text. Do you know how to make it to all the words "has" in our text? – Eugene Or Sep 23 '16 at 17:16
  • What do you mean `good decision`? You can use this idea to apply to other strings as well. – Santosh Sep 23 '16 at 17:24
  • I mean if we have the string | var stringOne = "Swift 3 has come, has has has come"; let stringTwo = "has" | It will color only first "has" in the stringOne. But how we can color all 4 words "has" in our string? Thank You – Eugene Or Sep 23 '16 at 17:30
  • Write a regular expression! – Santosh Sep 23 '16 at 17:59
  • thanks it helped me in my case and i hv given upvote @Santosh – Dilip Tiwari Aug 23 '18 at 18:30