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

时间:2016-11-09 22:51:03

标签: ios swift uitextview swift3

我有一个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 个答案:

答案 0 :(得分:1)

使用计时器。在物业中存放火柴。在属性中存储未突出显示的基础字符串。现在让你的计时器突出显示第一场比赛并在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)
        }
    }