如何在Swift中逐个更改UITextView中某些单词的样式?

我有一个UITextView ,其中有许多不同的单词彼此相邻。 当用户进入该屏幕时,我想开始突出显示一些单词,例如:

他看到的第一个是文本墙:

 one two three #four five six #seven eight nine ten eleven #twelve thirteen fourteen fifteen sixteen some other words #example test whatever #some thing 

然后,一秒后,单词four会改变样式(颜色),所以他会看到:

 one two three #FOUR five six #seven eight nine ten eleven #twelve thirteen fourteen fifteen sixteen some other words #example test whatever #some thing 

然后,一秒钟后,另一个单词会突出显示(并加入已经有色的four ):

 one two three #FOUR five six #SEVEN eight nine ten eleven #twelve thirteen fourteen fifteen sixteen some other words #example test whatever #some thing 

等等。 所以几秒钟后用户会看到:

 one two three #FOUR five six #SEVEN eight nine ten eleven #TWELVE thirteen fourteen fifteen sixteen some other words #EXAMPLE test whatever #SOME thing 

然后文本应该保持这样。 我怎样才能做到这一点?

我想过循环翻译单词并检查它们是否等于预定义的单词,但我不知道如何咬它 – 你能帮助我吗?

=====编辑

因此,为了让自己更容易,我决定用#符号标记突出显示的单词。

我有扩展名来突出显示textView中以#开头的所有单词:

 extension UITextView { func formatTextInTextView() { self.isScrollEnabled = false let selectedRange = self.selectedRange let text = self.text let font = UIFont(name: "AppleSDGothicNeo-Light", size: 16.0) let titleDict: NSDictionary = [NSFontAttributeName: font!] // This will give me an attributedString with the desired font let attributedString = NSMutableAttributedString(string: text!, attributes: titleDict as! [String : AnyObject]) let regex = try? NSRegularExpression(pattern: "#(\\w+)", options: []) let matches = regex!.matches(in: text!, options: [], range: NSMakeRange(0, (text?.characters.count)!)) for match in matches { let matchRange = match.rangeAt(0) let titleDict: NSDictionary = [NSForegroundColorAttributeName: orangeColor] attributedString.addAttributes(titleDict as! [String : AnyObject], range: matchRange) } self.attributedText = attributedString self.selectedRange = selectedRange self.isScrollEnabled = true } } 

但我不知道如何用一秒延迟分别突出每个单词

使用计时器。 在物业中存放火柴。 在属性中存储未突出显示的基础字符串。 现在让你的计时器突出显示第一场比赛并在1秒内再次自我调用,突出显示第二场比赛并重复直到没有比赛为止。

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