for循环

时间:2016-08-20 11:38:57

标签: ios swift nsattributedstring

我使用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
    } 
}

它只会改变第一个" "它找到了。

这是输出:

Example output

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

我会使用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
}