简体   繁体   English

在UITextfield中使用NSNumberFormatter进行实时格式化

[英]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 ($ .##). 我有UITextfield,用户可以输入一个美元金额,我希望textfield总是用两位小数格式化($。##)。 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 在.h文件中定义NSMutableString

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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