user11100093
user11100093

Reputation:

Not able to give separate color for multiple words

I'm having a certain sentence. I have to give black color to four words in that sentence.

This is how I have attempted that...

In viewDidLoad,

rangeArray = ["Knowledge","Events","Community","Offers"]

    for text in rangeArray {
      let range = (bottomTextLabel.text! as NSString).range(of: text)

      let attribute = NSMutableAttributedString.init(string: bottomTextLabel.text!)
      attribute.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.black , range: range)

      self.bottomTextLabel.attributedText = attribute
    }

But with this code, instead of having black color for all 4 words, I get only the word 'Offers' in black color. What am I doing wrong...?

Upvotes: 0

Views: 39

Answers (1)

PGDev
PGDev

Reputation: 24341

In your code, you are updating the self.bottomTextLabel.attributedText for each run of the for loop.

Instead of that you must

  1. create an NSMutableAttributedString using the sentence,
  2. add all the relevant attributes as per your rangeArray and
  3. then at last set that attrStr it as attributedText of bottomTextLabel.

Here is what I mean to say,

if let sentence = bottomTextLabel.text {
    let rangeArray = ["Knowledge","Events","Community","Offers"]
    let attrStr = NSMutableAttributedString(string: sentence)
    rangeArray.forEach {
        let range = (sentence as NSString).range(of: $0)
        attrStr.addAttribute(.foregroundColor, value: UIColor.black, range: range)
    }
    self.bottomTextLabel.attributedText = attrStr
}

Upvotes: 1

Related Questions