這是一個跟進這個問題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