如何通过格式化格式化的数字来设置TextField的字符长度

时间:2011-11-16 14:01:22

标签: iphone objective-c ios ipad ios4

我使用下面的代码将字符lentgh设置为17:

 - (BOOL)textField:(UITextField *)theTextField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
//    NSString *stringWithoutSpaces = [theTextField.text stringByReplacingOccurrencesOfString:@"," withString:@""];
    int limit = 16;
    switch (theTextField.tag) {
        case 10:
            NSLog(@"I m In 10");
            //To set maximum No.of Charaters.
            return !([theTextField.text length]>limit && [string length] > range.length);
            break;
        case 11:
            NSLog(@"I m In 11");
            //To set maximum No.of Charaters.
            return !([theTextField.text length]>limit && [string length] > range.length);
            break;
        default:
            NSLog(@"I m In default");
            break;
    }
    return YES;
} 

我正在textfieldShouldEndEditing

格式化输入的字符

例如, 我输入12345678912345678,其限制最多为17,格式为12,345,678,912,345,678  我们再次返回TextField,然后我们编辑为12,345,678,912,345,然后将,(逗号)视为一个字符,因此TextField的长度会增加。

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

简单的解决方案:

NSString *stringNumber = @"12,345,678,912,345";
NSUInteger length = [[stringNumber stringByReplacingOccurrencesOfString:@"," withString:@""] length];
NSLog(@"length: %lu", length);

NSLog输出:

length: 14

使用数字格式化程序。

示例:

NSString *stringNumber = @"12,345,678,912,345";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber *number = [formatter numberFromString:stringNumber];
NSLog(@"number: %@", number);
stringNumber = [number stringValue];
NSLog(@"stringNumber: %@", stringNumber);

NSLog输出:

number: 12345678912345
stringNumber: 12345678912345