Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

iphone - 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];
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...