UITextField:在input时限制允许的最大值(数字)
我有一个UITextField
,我想限制在该字段中允许的最大input值为1000.这是当用户在内部input数字时,一旦input值大于999,input字段中的值将不会更新除非用户input小于1000的值。
我想我应该使用UITextField
委托来限制input:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //How to do }
但我不知道如何实现它。 有什么build议么?
==========更新=============
我的input字段不仅允许用户input整数,而且浮点值如999,03
你应该在上面的方法里面做下面的事情:
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; //first, check if the new string is numeric only. If not, return NO; NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789,."] invertedSet]; if ([newString rangeOfCharacterFromSet:characterSet].location != NSNotFound) { return NO; } return [newString doubleValue] < 1000;
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { if(textField.tag == 3) { if(textField.text.length >3 && range.length == 0) { return NO; } else { return YES; } } }
我用你的项目中的任何地方的帮助方法创build了一个类。
SWIFT代码:
class TextFieldUtil: NSObject { //Here I am using integer as max value, but can change as you need class func validateMaxValue(textField: UITextField, maxValue: Int, range: NSRange, replacementString string: String) -> Bool { let newString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string) //if delete all characteres from textfield if(newString.isEmpty) { return true } //check if the string is a valid number let numberValue = Int(newString) if(numberValue == nil) { return false } return numberValue <= maxValue } }
然后,您可以在您的uiviewcontroller中,在任何文本字段validation的文本字段委托方法中使用
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { if(textField == self.ageTextField) { return TextFieldUtil.validateMaxValue(textField, maxValue: 100, range: range, replacementString: string) } else if(textField == self.anyOtherTextField) { return TextFieldUtils.validateMaxValue(textField, maxValue: 1200, range: range, replacementString: string) } return true }
if([string length]) { if (textField == txt) { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; return !([newString length] > 1000); } }
在其最基本的forms,你可以这样做:
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string { NSString* newText; newText = [textField.text stringByReplacingCharactersInRange:range withString:string]; return [newText intValue] < 1000; }
但是,您还需要检查newText
是否为整数,因为当文本以其他字符开头时, intValue
返回0。