2016-08-20 101 views
0

我用attributedString来改变textView文本的一部分的颜色。问题在于它只会改变它找到的第一个字符串的颜色,并且区分大小写。我希望它改变文本中所有相同字符串的颜色。任何人都知道如何为它编写一个循环? 这里是我的代码belongsString和textView颜色变化for循环

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

+1

所以你要整个字符串的颜色为红色?或者你想'爱'''L'是小写字母的红色?还是其他什么? – Lion

回答

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

NSRegularExpression使用基于UTF-16的范围,'s.characters.count'应该是's.utf16.count'。 – OOPer

+0

@OOPer谢谢,修复 – Kubba

+0

非常感谢。而已。 –

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 
}