0

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

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

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

什么是最干净的实现?

4

1 回答 1

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];
}
于 2011-08-10T16:52:48.820 回答