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

do *_*ter 1 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
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*eur 8

试试这个:

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
}
Run Code Online (Sandbox Code Playgroud)

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