iDeveloper iDeveloper - 5 months ago 23
Objective-C Question

How to set a range of numbers for textfield in iOS?

I want to set a range i.e between $350000 & $800000 for a text field. If the entered number is less than this range then an alert message should pop up. Plz help


In Objective-C using NSNumberFormatter you can use like this:

NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];

nf.minimum = @10;
nf.maximum = @20;

NSNumber *a = [nf numberFromString:@"12"];
NSNumber *b = [nf numberFromString:@"22"]; 
//if the number is beyond the range, it will return nil, so in above b is nil
//so the following check will show the log and alert

if (!a || !b) {
    NSLog(@"Either of them is out of range");
    //show the UIAlert here


You should call the above in following scenarios:

  1. User enter a value and does some action. In the beginning of the action use the above.

  2. Or every time the user enters and moves away from the textfield, then call the above in textFieldDidEndEditing: delegate method of UITextField.

Note: Since your number has $ prefixed, please make sure you set the currency style in nf as well, instead of trimming it.