Moeen.V Moeen.V - 1 year ago 99
Swift Question

attributedString and textView color change in a for loop

I used

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() {

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 Source
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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download