Форматирование в реальном времени с NSNumberFormatter в UITextfield

У меня есть UITextfield, где пользователь может вставить сумму в долларах, я хотел бы, чтобы текстовое поле всегда было отформатировано с двумя десятичными числами ($.##). Форматирование должно сохраняться все время. Но я застреваю о том, как добавить введенные номера к существующим в текстовом поле?

//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];
}
6
задан Oysio 9 March 2010 в 20:55
поделиться

1 ответ

Вот идея ...

Сохраните строковое значение, добавьте к нему, а затем используйте его для операции.

Определите NSMutableString в файле .h

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

Синтезируйте его.

Затем сделайте это ...

- (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;
}
2
ответ дан 17 December 2019 в 20:30
поделиться
Другие вопросы по тегам:

Похожие вопросы: