如何阻止在UITextField上输入非英文字符?

时间:2015-10-05 14:58:08

标签: swift

我试图阻止在UITextField上输入非英文字母。因此,我写了下面的方法。但它错误,因为"不能减少startIndex"通常。我已经阅读了一些有用的Stackoverflow帖子,但所有帖子都是用obj-c编写的。如何阻止非英文字母?

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let englishLetters = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
        let lastStringText = airportNameField.text?.substringFromIndex((airportNameField.text?.endIndex.advancedBy(-1))!)
        if englishLetters.indexOf(lastStringText!) == nil {
            airportNameField.deleteBackward()
    }
    return true
}

2 个答案:

答案 0 :(得分:7)

试试这个:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    /* So first we take the inverted set of the characters we want to keep,
       this will act as the separator set, i.e. those characters we want to
       take out from the user input */
    let inverseSet = NSCharacterSet(charactersInString:"ABCDEFGHIJKLMNOPQRSTUVWXUZ").invertedSet

    /* We then use this separator set to remove those unwanted characters.
       So we are basically separating the characters we want to keep, by those
       we don't */
    let components = string.componentsSeparatedByCharactersInSet(inverseSet)

    /* We then join those characters together */
    let filtered = components.joinWithSeparator("")

    return string == filtered
}

确保您已将UITextFieldDelegate添加到您的班级,然后确保正确设置了textField的委托。

答案 1 :(得分:1)

快捷键4

我为地址字段实现了以下解决方案。您可以根据需要修改CharacterSet。

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    var characterSet = CharacterSet()
    characterSet.formUnion(.lowercaseLetters) // e.g. a,b,c..
    characterSet.formUnion(.uppercaseLetters) // e.g. A,B,C..
    characterSet.formUnion(.decimalDigits) // e.g. 1,2,3
    characterSet.formUnion(.whitespaces) // " "
    characterSet.insert(charactersIn: "@,&:-") // Specific Characters

    let invertedCharacterSet = characterSet.inverted
    let components = string.components(separatedBy: invertedCharacterSet)
    let filtered = components.joined(separator: "")

    return string == filtered
}