Click here to Skip to main content
15,039,149 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a UITextField that the user will enter an amount of money. I want to set it so it will show the users currency. I could do the following:
Objective-C
- (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;
}


That works. But I want it to show on startup, and while the user is typing the amount. The above code only works when the user is finished with that textField. How can I make the code in that method to show on startup and while the user is entering numbers.

I tried to change the method to shouldChangeTextInRange, but it gives a weird effect.
Posted

1 solution

To change something on startup you run some code in viewDidLoad.

The handling in shouldChangeTextInRange is correct like instackoverflow described.

What weird effect?

Tip 1: NSNumberFormatter should created only ONCE (high cost object)
Tip 2: convert to ARC (with the assisent in Edit->convert)
   
Comments
Member 11360293 10-Jun-15 2:08am
   
Thanks for the answer! This sample project my give you an idea of what I mean: https://jumpshare.com/b/PSW9i0N012RSgzFoW6Eb

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900