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

时间:2016-07-17 14:46:15

标签: ios swift uitextfield uitextfielddelegate

我试图将验证放在textField中以确保它只包含字母。它一直有效,直到我按退格键。

作为解决方法,我尝试创建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中找到了一些旧的硬壳答案,但它们似乎都不适合我。有关转到NSMutableCharacterSet路线进行验证的其他建议吗?

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

1 个答案:

答案 0 :(得分:2)

试试这个:

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
  }
}