跟踪并更改UITextView中文本的颜色



当用户在文本视图中键入时,我会查看每个单词,并看到它与我拥有的数组中的单词匹配。如果匹配,则将单词更改为蓝色,并将布尔变量didFindACertainWord设置为true(以确保只有一个单词为蓝色)。我能够成功地完成这一部分,但有几个错误:

  1. 我更改为蓝色的某个单词有效,但在字体之前键入的单词被更改,我在单词之后键入的任何单词也都是蓝色的(我不想要)我只想把某个单词改成蓝色,其他单词保持黑色,字体和以前一样

  2. 我不知道如何找出用户是否删除了某个单词。如果他们这样做了,我想将某个单词的颜色改回黑色(在他们删除了该单词的第一个字符之后),并将didFindACertainWord设置为false

这是我的textViewDidChange方法中的当前代码:

func textViewDidChange(_ textView: UITextView) {
//get last word typed
let size = textView.text.reversed().firstIndex(of: " ") ?? textView.text.count
let startWord = textView.text.index(textView.text.endIndex, offsetBy: -size)
let lastWord = textView.text[startWord...]
//check if last word is in array and we did not already find one
if certainWords.contains(String(lastWord)) && !didFindACertainWord {
didFindACertainWord = true
//change color of the word
let attributedString = NSMutableAttributedString.init(string: textView.text)
let range = (textView.text as NSString).range(of: String(lastWord))
attributedString.addAttributes([NSAttributedString.Key.foregroundColor: UIColor.blue, NSAttributedString.Key.font: UIFont(name: "Avenir-Roman", size: 18)], range: range)
textView.attributedText = attributedString
}
}

我缺少什么/如何才能成功做到这一点?附言:文本视图中所有文本的字体应为UIFont(name: "Avenir-Roman", size: 18)

我搜索每个单词是因为用户键入动作词后,如果下一个单词与动作词相关,我需要阅读它们以加粗。例如,如果用户键入"see Paris London Berlin to find the best food",则动作词为"see",粗体的相关单词为"Paris Italy France",不相关的单词(将使用常规字体)为"to find thebest">

对于第一个问题,这是因为您应该执行"else"大小写,并重置颜色和布尔值。您应该添加:

} else {
didFindACertainWord = false
textView.attributedText = attributedString
}

对于第二个,您不需要只处理最后一个单词,而是检查整个字符串中是否匹配。

没有测试,但它应该工作:

func textViewDidChange(_ textView: UITextView) {
let attributedString = NSMutableAttributedString(string: textView.text,
attributes: [.font: UIFont(name: "Avenir-Roman", size: 18)])
let allWords = attributedString.string.components(separatedBy: CharacterSet.whitespaces)
if let firstMatch = allWords.first(where: { return certainWords.contains($0)}) {
didFindACertainWord = true
let firstMatchRange = (attributedString.string as NSString).range(of: firstMatch)
attributedString.addAttribute(.foregroundColor, value: UIColor.blue, range: firstMatchRange)
} else {
didFindACertainWord = false
}
textView.attributedText = attributedString
}

最新更新