拥有UItextview的这个代表我希望删除已使用此委托的文本中的标记单词
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.hasPrefix("@"), let lastWordRange = (textView.text as NSString?)?.range(of: lastWord){
if self.search(in: lastWord), searchDuplicate(this: lastWord) == 1 {
let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
let attributedString = NSMutableAttributedString(string: lastWord, attributes: attributes)
textView.textStorage.replaceCharacters(in:lastWordRange, with:attributedString)
}else{
if searchDuplicate(this: lastWord) > 1 {
textView.text.removeSubrange(Range(uncheckedBounds: (lower: textView.text.index(textView.text.endIndex, offsetBy: -lastWord.characters.count ), upper: textView.text.endIndex)))
}
let realLW = lastWord.replacingOccurrences(of: "@", with: "")
textView.textStorage.replaceCharacters(in:lastWordRange, with:realLW)
}
}
return true
}
该函数用@格式检测一个单词并检查是否有效作为标记,但如果输入标记不是第一次它不会得到适当的格式,因为该范围只在第一个外观中检测到它我必须删除它,但在textview.text的替换文本中,所有单词都丢失了它们的格式。所以我怎么能检测出重复删除它的单词的范围。
答案 0 :(得分:0)
试试这个
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
if text == " " {
let newText = removeDuplicates(text: textView.attributedText.string ?? "")
let attributes = [NSForegroundColorAttributeName: UIColor.blue, NSFontAttributeName: self.textView.font!] as [String : Any]
let attributedString = NSMutableAttributedString(string: newText, attributes: attributes)
textView.attributedText = attributedString
}
return true
}
func removeDuplicates(text: String) -> String {
let words = text.components(separatedBy: " ")
let filtered = words.filter { $0.characters.first == "@" }
return Array(Set(filtered)).joined()
}