Mellon Mellon - 1 year ago 109
Objective-C Question

UITextField : restrict the maximum allowed value (number) during inputting

I have a

, I'd like to restrict the maximum allowed input value in the field to be 1000. That's when user is inputting number inside, once the input value is larger than 999, the value in input field won't be updated anymore unless user is inputting value less than 1000.

I think I should use
delegate to limit the input:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
//How to do

But I am not sure how to implement it. Any suggestions?


my input field not only allow user to input integer, but also float value like 999,03

Answer Source

You should do the following inside the above method:

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download