开发者

How do I build a calculator-style number input field in iOS?

I already know how to enable the numeric keyboards and validate the field input to ensure it's numeric. What I want to know is how to set up an input view that'll let my user enter a number value from right to left, like a calculator or ATM machine.

In other words, I want the user to be able to type:

2 0 0 4 9

and have that be displayed as $200.49.

Then, once that's been input, I also need to get values in or out of this input view as an NSNumber开发者_如何学Go or NSDecimalNumber, with correct decimal placement.

For example, I have an NSDecimalNumber equivalent to 17.50. I need to be able to pass this number into the keypad view for editing, then get back the edited value as a number object.

Say the user edits that value; the value they see would be

1 7 5 0

Then they hit the backspace key. The number displayed would then be

1 7 5

I need to get that number back as 1.75, not 175 or 17.5.

Any suggestions?


To format the string you can use NSNumberFormatter. Something like this:

float input = 20049.0f / 100.0;

NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init];    
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle];

NSNumber *nsInput = [NSNumber numberWithFloat:input];
NSString* formattedOutput = [formatter stringFromNumber:nsInput];
NSLog(@"Output as currency: %@", formattedOutput);

[formatter release];


I have implemented SATextField that has this functionality built-in. It works just like a UITextField and has the same appearance. Merely set the fixedDecimalPoint property to YES.

EDIT: I have created a new project that contains this functionality: STAControls (specifically, use STAATMTextField -- it even supports . entry!). The difference is that this project has been implemented as a legitimate subclass of UITextField whereas SATextField was merely a container class housing a UITextField instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜