Swift 从UITextView中删除重复单词
拥有UItextview的此委托后,我想删除此委托文本中已存在的标记词Swift 从UITextView中删除重复单词,swift,nsstring,uitextview,nsrange,Swift,Nsstring,Uitextview,Nsrange,拥有UItextview的此委托后,我想删除此委托文本中已存在的标记词 func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { if text == " ",let lastWord = textView.text.components(separatedBy: " ").last, lastWord.hasPre
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
}
函数detect a word with@format并检查是否作为标记有效,但如果标记不是第一次输入,它将不会获得批准的格式,因为范围仅在第一次出现时检测到它,因此我必须删除它,但在textview的替换文本中。text all word失去了格式。因此,我如何检测重复删除的单词的范围 试试这个
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()
}
先替换为.characters.first