删除UITextField中的重复条目

时间:2019-06-09 16:11:28

标签: ios swift duplicates uitextfield

我必须在UITextField中输入值时删除重复的条目。 有没有一种方法可以在输入UITextField时检查重复项?假设我在用单个空格“”分隔的UITextField中输入一些文本。如果输入重复项,我需要“动态”检查。换句话说,有没有一种方法可以禁用UITextField中的重复项?

1 个答案:

答案 0 :(得分:0)

您应该实现UITextField操作.editingChanged:

textField.addTarget(self, action: #selector(self.textFieldEditingChanged(_:)), for: .editingChanged)

并检查文本:

@objc
func textFieldEditingChanged(_ sender: UITextField) {
    guard let text = sender.text else { return }
    var finishedWords = text.components(separatedBy: " ").filter({ $0 != "" })
    var endOfResult = ""

    if text.last == " " {
        endOfResult = " "
    } else if !finishedWords.isEmpty {
        if finishedWords.count > 1 {
            endOfResult += " "
        }
        endOfResult += finishedWords.last ?? ""
        finishedWords.removeLast()
    }

    var seen = [String]()
    let uniqueWords = finishedWords.filter({ word in
        if seen.contains(word) {
            return false
        } else {
            seen.append(word)
            return true
        }
    })

    let result = uniqueWords.joined(separator: " ") + endOfResult
    sender.text = result
}