0

因此,当用户输入生日时,我尝试在 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;
}
4

2 回答 2

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:@"/"];
  }
于 2013-10-01T18:17:35.440 回答
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;
}
于 2013-10-02T00:18:59.527 回答