Reputation:
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
Reputation: 24341
In your code, you are updating the self.bottomTextLabel.attributedText
for each run of the for loop
.
Instead of that you must
NSMutableAttributedString
using the sentence
, attributes
as per your rangeArray
and 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