Форматирование в реальном времени с NSNumberFormatter в поле UIText - PullRequest
6 голосов
/ 09 марта 2010

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

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

1 Ответ

2 голосов
/ 10 марта 2010

Вот идея ...

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

Определить 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;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...