objective-ccocoansnumberformatternsformatter

NSTextField with number formatter does not accept padding character only


I have a NSTextField with a number formatter set this way:

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

[myFormatter setFormatWidth:7];
[myFormatter setPaddingCharacter:@"0"];
[myFormatter setMinimumSignificantDigits:0];

[myFormatter setMinimum:[NSNumber numberWithInteger:0]];
[myFormatter setMaximum:[NSNumber numberWithInteger:9999999]];
[myClientIDTextField setFormatter:myFormatter];

Everything works as expected, but I cannot input "0" or "00" or "000" and so on in the textfield, if I do a sheet appears on the window, saying that my input was invalid. My expected behaviour would be that inputting "0" should be validated as "0000000". Does anybody have a clue of why this is happening and how to solve this ?

Thanks


Solution

  • If you specify the format as @"0000000", then it requires 7 digits and will fill in 0s where a digit doesn't exist.

    // Objective-C
    NSNumberFormatter *myFormatter = [[NSNumberFormatter alloc] init];
    [myFormatter setFormat:@"0000000"];
    [myFormatter setMinimum:@0];
    [myFormatter setMaximum:@9999999];
    [myClientIDTextField setFormatter:myFormatter];
    
    // Swift
    let myFormatter = NumberFormatter()
    myFormatter.format = "0000000"
    myFormatter.minimum = 0
    myFormatter.maximum = 9999999
    myClientIDTextField.formatter = myFormatter
    

    Hope that helps.