for 循环中的 attributedString 和 textView 颜色变化

attributedString and textView color change in a for loop

我用attributedString改变了textView中部分文字的颜色。问题是它只改变它找到的第一个字符串的颜色并且区分大小写。我想让它改变文本中所有相同字符串的颜色。任何人都知道如何为它编写一个循环? 这是我的代码

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
    } 
}

它只会更改它找到的第一个“love”。

这是输出:

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)
}

我会使用NSRegularExpression,但如果你更喜欢rangeOfString方法,你可以这样写:

let text = "Love ,love, love, love, Love"
let linkTextWithColor = "love"

var startLocation = 0
let attributedString = NSMutableAttributedString(string:text)
while case let range = (text as NSString).rangeOfString(linkTextWithColor,
                                                        options: [.CaseInsensitiveSearch],
                                                        range: NSRange(startLocation..<text.utf16.count))
    where range.location != NSNotFound
{
    attributedString.addAttribute(NSForegroundColorAttributeName,
                                  value: UIColor.redColor(),
                                  range: range)
    startLocation += range.length
}