NSNumberFormatter无法允许数字以0开头

时间:2013-10-01 18:04:25

标签: objective-c nsstring nsnumberformatter

所以我试图在用户进入他们的生日时自动在2位数之间添加斜杠,但由于某种原因,当生日以0开始时,数字格式化程序会删除它并弄乱生日。我在下面有我的代码,有人可以帮我弄明白怎么做吗?提前谢谢!

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;
}

2 个答案:

答案 0 :(得分:1)

这样的事情可能有所帮助:

  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:@"/"];
  }

答案 1 :(得分:1)

您可以做的是:

  • 检查字符串的长度
  • 如果长度mod 2 == 0则添加“/”
  • 记录您的字符串

说这是推荐的,但它可能对你有所帮助!

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

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