使用 shouldChangeCharactersInRange 计算 UITextField 验证中的退格

Accounting for backspace in UITextField validation using shouldChangeCharactersInRange

我试图在文本字段中进行验证以确保它只包含字母。它一直有效,直到我按下退格键。

作为解决方法,我尝试创建一个 NSMutableCharacterSet 并使用 formUnionWithCharacterSet 添加 NSCharacterSet.letterCharacterSet()。然后我给它加了退格键。那也行不通。

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {        
    // Limit to Letters & Backspace
    // let charactersAllowed = NSCharacterSet.letterCharacterSet()
    let charactersAllowed = NSMutableCharacterSet()
    charactersAllowed.formUnionWithCharacterSet(NSCharacterSet.letterCharacterSet())
    charactersAllowed.addCharactersInString("\b")

    if let rangeOfCharactersAllowed = string.rangeOfCharacterFromSet(charactersAllowed, options: .CaseInsensitiveSearch) {
        return rangeOfCharactersAllowed.count == string.characters.count
    } else {
        displayAlert("Invalid Character", alertMessage: "Please enter only letters")
        return false
    }
}

我在 Objective-C 中找到了一些老掉牙的答案,但其中 none 似乎对我有用。关于转到 NSMutableCharacterSet 验证路线的任何其他建议?

如果有帮助,我正在使用模拟器并尝试按键盘右上角的退格键(删除)。

试试这个:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
  let notLetterSet = NSCharacterSet.letterCharacterSet().invertedSet
  let textFieldInvalidCharPosition = string.rangeOfCharacterFromSet(notLetterSet)

if (textFieldInvalidCharPosition != nil) {
     return false
  } else {
     return true
  }
}