如何在swift 2.0中只允许UITextfield中的某些数字

我有一个UITextField中,我得到的月份号码作为input。 我成功地将UITextField中的字符数限制为2。 但是我希望用户只input从1 to 12的值,而不是其他值。 这必须同时完成,当用户input数字,即在func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool 。 如果我使用一个简单的if条件来检查每个字符并在else部分返回false,那么textfield将不允许我使用清除或重新input任何其他字符。 谁来帮帮我。

将键盘types设置为数字键盘

添加这个

 func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool { if let text = textField.text { let newStr = (text as NSString) .stringByReplacingCharactersInRange(range, withString: string) if newStr.isEmpty { return true } let intvalue = Int(newStr) return (intvalue >= 0 && intvalue <= 12) } return true } 

您可以通过检查shouldChangeCharactersInRange中的TextField值来同时执行此操作。

 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { let inputStr = textField.text?.stringByAppendingString(string) let inputInt = Int(inputStr!) if inputInt > 0 && inputInt < 13 { return true } else { return false } } 

=>你可以像这样定义char的限制:

 #define NUMBERS_ONLY @"1234567890" #define CHARACTER_LIMIT 2 

=>和基于定义限制字符你可以使用,并尝试下面的方法: –

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSUInteger newLength = [textField.text length] + [string length] - range.length; NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet]; NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""]; return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT)); } 
 func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // Create an `NSCharacterSet` set which includes everything *but* the digits let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet // At every character in this "inverseSet" contained in the string, // split the string up into components which exclude the characters // in this inverse set let components = string.componentsSeparatedByCharactersInSet(inverseSet) // Rejoin these components let filtered = components.joinWithSeparator("") // use join("", components) if you are using Swift 1.2 // If the original string is equal to the filtered string, ie if no // inverse characters were present to be eliminated, the input is valid // and the statement returns true; else it returns false return string == filtered } 

请参阅此链接 – 将UITextFieldinput限制在Swift中的数字