I have a UITextView
with many different words next to each other. When user enters that screen I want to start highlighting some words, e.g.:
the first what
Use a timer. Stash matches in a property. Stash the base unhighlighted attributed string in a property. Now have your timer highlight the first match and call itself again in 1 second, highlighting up to the second match and repeat until there are no matches left.
func highlight (to index: Int = 0) {
guard index < matches.count else {
return
}
let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor]
let attributedString = NSMutableAttributedString(attributedString: storedAttributedString)
for i in 0..< index {
let matchRange = matches[i].rangeAt(0)
attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange)
}
self.attributedText = attributedString
let _ = Timer.scheduledTimer(withTimeInterval: 1, repeats: false) { _ in
self.highlight(to: index + 1)
}
}