There is an NSTextField field and you need to make it so that only numbers can be entered into it and that they look like this: "123-456-789"

This problem I solved NSNumberFormatter:

NSString *myString = @"12345678"; NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; [formatter setGroupingSeparator:@"-"]; [formatter setGroupingSize:3]; [formatter setMaximumIntegerDigits:9]; NSString *formattedOutput = [formatter stringFromNumber:[NSNumber numberWithInteger:[myString intValue]]]; 

But the problem is that the formatting takes place not on the right, but on the left, that is, we have:

"12-345-678",

but you need to be so: "123-456-78"

    3 answers 3

    I don’t know how this should be implemented using NSNumberFormatter, but you can manually add a separator. Something like that:

     // field - поле ввода (NSTextField) NSMutableString *temp = [NSMutableString stringWithString:[field stringValue]]; int index=3; if ([temp length] <=3) { return; } while (index < [temp length]) { [temp insertString:@"-" atIndex:index]; index +=4; } 

    Well, if, of course, you can enter only 8 or 9 digits, then the previous solution is more convenient.

    You need to track character input using NSNotification and insert a "-" after every 3 characters. When you get focus, go through the text and delete "-" After the end of the input, you also go through and add "-"

      Something I do not understand where the order is formed *** - *** - ** <br/> But logically, if <br/> *** - *** - ** => ** - *** - *** <br/> then you can do the opposite <br/> ** - *** - *** => *** - *** - ** <br/> and get what you need = ) <br/> PS: I’ll get to the computer later and try to figure it out

      UPD.

       [numberFormatter setPositiveFormat:@"###-###-##"]; 
      • This sets the delimiter: [formatter setGroupingSeparator:@"-"]; . This indicates how many digits in the group: [formatter setGroupingSize:3]; . - BUDDAx2
      • Try setPositiveFormat. - AlexDenisov
      • Does not work. - BUDDAx2
      • So it did not work out the problem. - BUDDAx2
      • But the option that I proposed - explain why not suitable? - VioLet 2:51 pm