使用UITextField格式化货币 [英] Format currency with UITextField

查看:106
本文介绍了使用UITextField格式化货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个UITextField,用户将输入一笔金额。我想设置它以便显示用户货币。我可以执行以下操作:

I have a UITextField that the user will enter an amount of money. I want to set it so it will show the users currency. I could do the following:

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSNumberFormatter *currencyFormatter = [[[NSNumberFormatter alloc] init] autorelease];
    [currencyFormatter setLocale:[NSLocale currentLocale]];
    [currencyFormatter setMaximumFractionDigits:2];
    [currencyFormatter setMinimumFractionDigits:2];
    [currencyFormatter setAlwaysShowsDecimalSeparator:YES];
    [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    NSNumber *someAmount = [NSNumber numberWithDouble:[textField.text doubleValue]];
    NSString *string = [currencyFormatter stringFromNumber:someAmount];

    textField.text = string;
}





有效。但是我希望它在启动时显示,并且当用户输入金额时。以上代码仅在用户完成该textField时才有效。如何在启动时和用户输入数字时显示该方法中的代码。



我试图将方法更改为shouldChangeTextInRange,但它给出了奇怪的效果。



That works. But I want it to show on startup, and while the user is typing the amount. The above code only works when the user is finished with that textField. How can I make the code in that method to show on startup and while the user is entering numbers.

I tried to change the method to shouldChangeTextInRange, but it gives a weird effect.

推荐答案

要在启动时更改某些内容,请在viewDidLoad中运行一些代码。



处理inChangeTextInRange是正确的,如 stackoverflow 所述。



有什么奇怪的效果?



提示1:NSNumberFormatter应该只创建ONCE(高成本对象)

提示2:转换为ARC(编辑 - >转换中的assisent)
To change something on startup you run some code in viewDidLoad.

The handling in shouldChangeTextInRange is correct like instackoverflow described.

What weird effect?

Tip 1: NSNumberFormatter should created only ONCE (high cost object)
Tip 2: convert to ARC (with the assisent in Edit->convert)


这篇关于使用UITextField格式化货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆