Удаление повторяющихся слов из UITextView

имея этот делегат 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 все слова потеряли свой формат. так как я могу определить диапазон слова, которое повторяется, чтобы удалить его.


person Community    schedule 14.11.2017    source источник


Ответы (1)


попробуй это

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()
}
person Yerkebulan Abildin    schedule 14.11.2017
comment
Просто замените на .characters.first - person Yerkebulan Abildin; 14.11.2017