-1

I have a UITextField. I'd like to restrict the maximum allowed input value in the field to be 10.

That is, when the user is inputting the number inside, once the input value is larger than 10, the value in the input field won't be updated anymore unless the user is inputting a value less than or equal to 10.

Pang
  • 9,564
  • 146
  • 81
  • 122

2 Answers2

0

All the other answers are limiting the length of the input, while the OP is clearly asking for a limit to the value of the input. First of all, you can also use a UIStepper


(source: apple.com)

or a UISlider for this purpose (together with a label to display the current value). This might be clearer to the user as well.

If you stick to a UITextField-based approach, you need to implement the textField:shouldChangeCharactersInRange:replacementString: method as follows:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    NSNumberFormatter *numberFormatter = [NSNumberFormatter new];
    NSNumber *number = [numberFormatter numberFromString:text];
    if (number == nil || [number doubleValue] > 10) {
        return NO;
    }
    return YES;
}

You might want to add some extra checks for negative numbers if you don't allow them.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
-2

Try this:

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{
if(textField == mytextField)
{
 if (textField.text.length == 10)
        {
            if (range.length == 0)
            {
                return NO;
            }
        }
return YES;
}
}

--> It will definetely help you

Good Luck

Jecky
  • 476
  • 1
  • 4
  • 21