Search code examples
iosuitextfieldnsnumberformatter

Set a UITextField to write a maximum of 11 numbers using NSNumberFormatter


i’m trying to configure a UITExtField to only accept 11 numbers, i’m using NSNumberFormatter and it works just fine with using numbers, but when I try to set the maximum numbers available it doesn’t work.

Even assigning setMaximumFractionDigits, setMaximumIntegerDigits and setMaximumSignificantDigits it doesn’t work like it should, or Am i missing something? please help.

here’s my code…

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

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

[num setNumberStyle:NSNumberFormatterDecimalStyle];
[num setUsesSignificantDigits:YES];
[num setMaximumFractionDigits:0];
[num setMaximumIntegerDigits:11];
[num setMaximumSignificantDigits:11];

NSString *aString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 
//[NSString stringWithFormat:@"%@%@", textField.text, string];
NSNumber *number = [num numberFromString:aString];

if (number) {
    return YES;
else
    return NO;
}

EDIT:

I reordered the code like Ian said and made the changes that Ink said too and still the same, i can write numbers only but i can write more than 11 numbers.

EDIT 2

Thanks Ian and Ink, now it works, I needed to check that aString.length were minor than 12 and it were a number.

    if (aString.length < 12 && number)
        return YES;
    else
        return NO;

Thanks for any help!


Solution

  • You are assigning number before setting your constraints on num... Try this instead:

    [num setUsesSignificantDigits:YES];
    [num setMaximumFractionDigits:0];
    [num setMaximumIntegerDigits:11];
    [num setMaximumSignificantDigits:11];
    
    NSNumber *number = [num numberFromString:aString];
    
    if (number) {
      return [[num stringFromNumber:number] length] <= 11 && [[num stringFromNumber:number] length] == [aString length];
    } else {
      return NO;
    }