Realtime formatting with NSNumberFormatter in a UITextfield

后端 未结 1 1990
遥遥无期
遥遥无期 2020-12-09 13:33

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

相关标签:
1条回答
  • 2020-12-09 14:01

    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;
    }
    
    0 讨论(0)
提交回复
热议问题