Frage

So I'm attempting to automatically add slashes between 2 digits when a user enters in their birthday, but for some reason when the birthday starts with a 0, the number formatter erases it and messes up the birthday. I've got my code below, could someone help me figure out how to do this? Thanks in advance!

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

[formatter setGroupingSeparator:@"/"];
[formatter setGroupingSize:2];
[formatter setUsesGroupingSeparator:YES];
[formatter setSecondaryGroupingSize:2];
NSString *num = textField.text ;
if(![num isEqualToString:@""])
{
    num= [num stringByReplacingOccurrencesOfString:@"/" withString:@""];
   NSString *str = [formatter stringFromNumber:[NSNumber numberWithDouble:[num doubleValue]]];
    textField.text=str;
}
War es hilfreich?

Lösung

What you could do is the following:

  • Check the length of the string
  • If length mod 2 == 0 then add "/"
  • Log your string

I'm not saying this is recommended but it might help you a bit!

- (void)controlTextDidChange:(NSNotification *)obj{
    NSString *num = [textField stringValue] ;

    if (num.length%2==0)
    {
        NSString *someText = [NSString stringWithFormat: @"%@/ ", num];
        num = someText;
    }
    textField.stringValue = num;
}

Andere Tipps

Something like this may help:

  NSMutableString *string = @"YOUR TEXTFIELD TEXT";
  NSString *lastString = [string substringWithRange:NSMakeRange(string.length-2, 1)];
  if ([lastString isEqualToString:@"/"]) {
    return;
  }
  if (string.length == 2 || string.length == 5) {
    [string appendString:@"/"];
  }
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top