gpt4 book ai didi

ios - 跟踪和更改 UITextView 中文本的颜色

转载 作者:搜寻专家 更新时间:2023-10-31 22:37:20 27 4
gpt4 key购买 nike

当用户在 TextView 中输入内容时,我会查看每个单词并查看它是否与我拥有的数组中的单词相匹配。如果匹配,则该词变为蓝色并且 bool 变量 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
}
}

我错过了什么/我怎样才能成功做到这一点?附言 TextView 中所有文本的字体应为 UIFont(name: "Avenir-Roman", size: 18)

我正在搜索每个词,因为在用户键入一个 Action 词后,如果它们与 Action 词相关,我需要阅读下一个词以将它们加粗。例如,如果用户输入“see Paris London Berlin to find the best food”, Action 词是“see”,相关词加粗是地点“Paris Italy France”和不相关的词(将以常规形式显示)字体)是“找到最好的”

最佳答案

对于第一个问题,这是因为你应该做一个“else”案例,并重置颜色和 bool 值。你应该添加:

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

关于ios - 跟踪和更改 UITextView 中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54164170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com