Moeen.V Moeen.V - 3 months ago 13
Swift Question

attributedString and textView color change in a for loop

I used

attributedString
to change the color of a part of the text in the textView. The problem is that it only changes the color of the first string that it finds and It's case sensitive. I want it to change the color of all same strings in the text. Anyone knows how to write a loop for it?
Here is my code

class ViewController: UIViewController {
@IBOutlet var textView: UITextField!
@IBOutlet var textBox: UITextField!
override func viewDidLoad() {
super.viewDidLoad()

let text = "Love ,love, love, love, Love"
let linkTextWithColor = "love"
let range = (text as NSString).rangeOfString(linkTextWithColor)

let attributedString = NSMutableAttributedString(string:text)
attributedString.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor() , range: range)

self.textView.attributedText = attributedString
}
}


It only changes the first "love" that it finds.

Here is the output:

Example output

Answer
let s = "love, Love, lOVE, LOVE"

let regex = try! NSRegularExpression(pattern: "love", options: .CaseInsensitive)

let matches = regex.matchesInString(s, options: .WithoutAnchoringBounds, range: NSRange(location: 0, length: s.utf16.count))

let attributedString = NSMutableAttributedString(string: s)

for m in matches {
    attributedString.addAttributes([NSForegroundColorAttributeName: UIColor.redColor()], range: m.range)
}