How can I change style of some words in my UITextView one by one in Swift?

前端 未结 1 787
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 04:11

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

相关标签:
1条回答
  • 2021-01-25 05:06

    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)
            }
        }
    
    0 讨论(0)
提交回复
热议问题