使用UITextField格式化货币

我有一个用户将input一笔钱的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; } 

这样可行。 但我希望它在启动时显示,并在用户input金额。 上述代码仅在用户使用该文本字段完成时才起作用。 如何使该方法中的代码在启动时以及用户input数字时显示。

我试图将方法更改为shouldChangeTextInRange ,但它给出了一个奇怪的效果。

如果你使用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; }]; 

这不是完美的,但也许这可以帮助你find正确的解决scheme。