这是一个跟进这个问题How can I change style of some words in my UITextView one by one in Swift?如何在我的textView中更改预选词的样式?
感谢@约什的帮助,我写的一段代码,可以突出与#
开头单词 - 而且做一个接一个。我对于最终的代码是:
func highlight (to index: Int) {
let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: [])
let matches = regex!.matches(in: hashtagExplanationTextView.text, options: [], range: NSMakeRange(0, (hashtagExplanationTextView.text.characters.count)))
let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]
let titleDict2: NSDictionary = [NSForegroundColorAttributeName: UIColor.red]
let storedAttributedString = NSMutableAttributedString(string: hashtagExplanationTextView.text!, attributes: titleDict as! [String : AnyObject])
let attributedString = NSMutableAttributedString(attributedString: storedAttributedString)
guard index < matches.count else {
return
}
for i in 0..<index{
let matchRange = matches[i].rangeAt(0)
attributedString.addAttributes(titleDict2 as! [String : AnyObject], range: matchRange)
}
hashtagExplanationTextView.attributedText = attributedString
if #available(iOS 10.0, *) {
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
self.highlight(to: index + 1)
}
} else {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.highlight(to: index + 1)
}
}
}
这工作得很好,但我想改变的逻辑,这样它不突出#
话,但这些话预选阵列亮点(一一)字样。
所以我有这样的阵列var myArray:[String] = ["those","words","are","highlighted"]
,我怎么可以把它代替正则表达式匹配的在我的代码?
你有什么话对的阵列匹配方面到目前为止已经试过?自从我的单词列表 –
@Patrick很短(我有一个5人6)我试图修改正则表达式,但它并不能很好的工作,因为换句话说也被捉住。我也试图直接提供的话'matches',但随后的进一步逻辑没有工作 – user3766930