简体   繁体   中英

Realtime formatting with NSNumberFormatter in a UITextfield

I have UITextfield where a user can put in a dollar amount, I would like the textfield always to be formatted with two decimals ($ .##). The formatting has to be maintained all the time. But i'm stuck on how to append the entered numbers to existing ones in the textfield ?

//This delegate is called everytime a character is inserted in an UITextfield.
- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([textField tag] == amountTag)
    {

        NSString *amount = string;

//How do I append the already entered numbers in the textfield to the new entered values   ?
//??

        //Get new formatted value
        NSString *newAmount = [self formatCurrencyValue:[amount doubleValue]];

        [textField setText:[NSString stringWithFormat:@"%@",newAmount]];

        return NO;
    }

    //Returning yes allows the entered chars to be processed
    return YES;
}


-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init]autorelease];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

Here's the idea...

Store the string value, append to it, then use that for the operation.

Define an NSMutableString in the .h file

NSMutableString *storedValue;
@property (nonatomic, retain) NSMutableString *storedValue;

Synthesize it.

Then do this...

- (BOOL) textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
   if ([textField tag] == amountTag)
    {
    [storedValue appendString:string];
    NSString *newAmount = [self formatCurrencyValue:([storedValue doubleValue]/100)];

    [textField setText:[NSString stringWithFormat:@"%@",newAmount]];
    return NO;
    }

    //Returning yes allows the entered chars to be processed
    return YES;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM