Mel*_*emi 6 cocoa cocoa-touch currency uitextfield
我正在尝试做一些我认为相当简单的事情:让用户输入一个美元金额,将该金额存储在NSNumber(NSDecimalNumber?)中,然后在稍后的某个时间再次显示格式化为货币的金额.
我的麻烦不在于setNumberStyle:NSNumberFormatterCurrencyStyle并将浮动显示为货币.问题更多的是所述numberFormatter如何与这个UITextField一起工作.我可以找到一些例子.这个帖子来自十一月,这个给我一些想法,但给我留下了更多的问题.
我正在使用UIKeyboardTypeNumberPad键盘并了解我应该在显示的字段中显示$ 0.00(或任何本地货币格式)然后当用户输入数字以移动小数位时:
然后[numberFormatter numberFromString:textField.text]应该给我一个值,我可以存储在我的NSNumber变量中.
可悲的是,我还在苦苦挣扎:这真的是最好/最简单的方式吗?如果是这样,也许有人可以帮助我实施?我觉得UITextField可能需要一个代理响应每个按键,但不知道什么,在哪里以及如何实现它?!任何示例代码?我非常感谢!我搜索过高低......
Edit1:所以我正在研究NSFormatter的stringForObjectValue:以及我能找到的最接近benzado建议的东西:UITextViewTextDidChangeNotification.很难在其中任何一个上找到示例代码......所以如果你知道在哪里看,请告诉我?
Lar*_*der 10
我的解决方案
- (BOOL)textField:(UITextField *)textField
shouldChangeCharactersInRange:(NSRange)range
replacementString:(NSString *)string
{
// Clear all characters that are not numbers
// (like currency symbols or dividers)
NSString *cleanCentString = [[textField.text
componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
// Parse final integer value
NSInteger centAmount = cleanCentString.integerValue;
// Check the user input
if (string.length > 0)
{
// Digit added
centAmount = centAmount * 10 + string.integerValue;
}
else
{
// Digit deleted
centAmount = centAmount / 10;
}
// Update call amount value
[_amount release];
_amount = [[NSNumber alloc] initWithFloat:(float)centAmount / 100.0f];
// Write amount with currency symbols to the textfield
NSNumberFormatter *_currencyFormatter = [[NSNumberFormatter alloc] init];
[_currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[_currencyFormatter setCurrencyCode:@"USD"];
[_currencyFormatter setNegativeFormat:@"-¤#,##0.00"];
textField.text = [_currencyFormatter stringFromNumber:_amount];
[_currencyFormatter release]
// Since we already wrote our changes to the textfield
// we don't want to change the textfield again
return NO;
}
如果我现在必须写的话,这是我会使用的粗略的攻击计划。诀窍是在隐藏的 UITextField 中键入内容,并在用户键入时使用格式化值更新 UILabel。
每次按键时,标签都会更新,因此当用户真正编辑隐藏文本字段时,她会感觉好像正在编辑格式化值。多么狡猾啊!
| 归档时间: |
|
| 查看次数: |
5455 次 |
| 最近记录: |