Use keypad to enter in currency value in desired f

2020-04-15 16:02发布

问题:

I want to have a screen that starts off with "$0.00" (or other symbol based on locale) that I can enter values into and it will update one at a time. (type 1234, returns $0.01, $0.12, $1.23, $12.34). I know how to do this with the digits entered into a text field and with the click of a button change the formatting either in the text field or into a new label. What I want, though, is to do it without the extra button tap and use a label, not a textField.

float moneyEarnedFloat = [revenueTextField.text floatValue]/100.0f;
NSNumber *moneyEarned = [NSNumber numberWithFloat:moneyEarnedFloat];
NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

revenueTextField.text = [currencyFormatter stringFromNumber:moneyEarned];

An example would be mint.com's Add Transaction screen.

回答1:

Try this:

NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
[currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
int currencyScale = [currencyFormatter maximumFractionDigits];

TextFieldDidChange:

[mytextField addTarget:self action:@selector(textFieldDidChange) forControlEvents:UIControlEventEditingChanged];

Then do:

    - (void)textFieldDidChange {
myLabel.text = mytextField.text;
}