当用户将数字输入UITextField时,如何使用NSNumberFormatter对数字进行分组?

时间:2011-07-18 15:55:44

标签: ios uitextfield nsnumberformatter

我想使用“。”将输入的数字分组到我的金额字段中。作为分组分隔符,如100.000

我实现了视图控制器的shouldChangeCharactersInRange方法,以便小数部分只允许数字和一个逗号,只能是2位数。

现在我想把分组分隔符作为用户实时输入数字。当我想到实现时,我对用户删除数字或诸如用户将光标放在开头并在输入的数字的前面键入0等事情感到困惑,等等......

什么是最干净的实施?

1 个答案:

答案 0 :(得分:0)

好的,方法如下:

首先,您实施UITextField类别。 然后你对自己说:

[self addTarget:self action:@selector(formatTextAsNumber) forControlEvents:UIControlEventEditingChanged];

这是魅力的formatTextAsNumber方法:

- (void)formatTextAsNumber {

    [self removeTarget:self action:@selector(formatTextAsNumber) forControlEvents:UIControlEventEditingChanged];

    if ([self.text length] > 0) {
        NSString *currentText = [NSString stringWithString:self.text];

        currentText = [currentText stringByReplacingOccurrencesOfString:kGroupingSeperator withString:@""];
        currentText = [currentText stringByReplacingOccurrencesOfString:@"," withString:@"."];

        NSString *suffix = [currentText substringFromIndex:[currentText length] - 1];

        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        NSLocale *trLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"tr_TR"] autorelease];
        [formatter setLocale:trLocale];

        NSNumber *number = [NSNumber numberWithDouble:[currentText doubleValue]];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
        [formatter setGroupingSeparator:@"."];

        NSString *finalText = [formatter stringFromNumber:number];

        if ([suffix isEqualToString:@"."]) {
            finalText = [finalText stringByAppendingString:@","];
        }

        self.text = finalText;
        [formatter release];
    }

    [self addTarget:self action:@selector(formatTextAsNumber) forControlEvents:UIControlEventEditingChanged];
}