使用UITextField格式化货币

时间:2015-06-09 20:56:02

标签: ios objective-c uitextfield

我有一个UITextField,用户将输入一笔金额。我想设置它,以便显示用户当前的货币。我可以做到以下几点:

- (void)textFieldDidEndEditing:(UITextField *)textField {

    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setMaximumFractionDigits:2];
    [currencyFormatter setMinimumFractionDigits:2];
    [currencyFormatter setAlwaysShowsDecimalSeparator:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
    NSString *string = [currencyFormatter stringFromNumber:someAmount];

    textField.text = string;
}

有效。但是我希望它在启动时显示,并且当用户输入金额时。以上代码仅在用户完成该textField时才有效。如何在启动时以及在用户输入数字时使该方法中的代码显示。

我尝试将方法更改为shouldChangeTextInRange,但它会产生奇怪的效果。

1 个答案:

答案 0 :(得分:0)

如果您正在使用ReactiveCocoa,可以尝试这样做。

[textField.rac_textSignal subscribeNext:^(NSString *text) {
    if (text.length < 4) text = @"0.00";

    //set currency style
    NSNumberFormatter *currencyFormatter = [NSNumberFormatter new];
    currencyFormatter.numberStyle = NSNumberFormatterCurrencyStyle;

    //leave only decimals (we want to get rid of any unwanted characters)

    NSString *decimals = [[text componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]] componentsJoinedByString:@""];

    //insert decimal separator
    NSMutableString *mutableString = [NSMutableString stringWithString:decimals];
    [mutableString insertString:currencyFormatter.decimalSeparator atIndex:mutableString.length - currencyFormatter.minimumFractionDigits];

    //I add currency symbol so that formatter recognizes decimal separator while formatting to NSNumber
    NSString *result = [currencyFormatter.currencySymbol stringByAppendingString:mutableString];

    NSNumber *formattedNumber = [currencyFormatter numberFromString:result];
    NSString *formattedText = [currencyFormatter stringFromNumber:formattedNumber];

    //saving cursors position 
    UITextRange *position = textField.selectedTextRange;

    textField.text = formattedText;

    //reassigning cursor position (Its not working properly due to commas etc.)
    textField.selectedTextRange = position;
}];

这并不完美,但也许这可以帮助您找到正确的解决方案。