2015-10-05 40 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____________ –

相關問題