2015-10-05 89 views
1

我想阻止在UITextField上输入非英文字母。因此,我写了下面的方法。但它的错误是“不能像往常一样递减startIndex”。我已经阅读了一些有用的Stackoverflow帖子,但所有这些都是用obj-c编写的。我怎样才能阻止非英文字母?如何阻止在UITextField上输入非英文字符?

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 
} 

回答

5

试试这个:

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到您的类,然后还要确保你的文本字段的委托设置是否正确。

+0

你能解释你的代码吗? –

+0

@twigofa,我已经更新,包括一些评论 - 希望它有帮助! –

+0

thanks____________ –

相关问题