如何在UITextfield中键入时输入货币符号?

时间:2012-11-22 21:47:55

标签: objective-c ios ios5 uitextfield currency

我正在使用这个股票市场计算器,我在StackOverFlow搜索Apple文档,互联网,但是没有成功找到答案..

我有一个UITextfield,用户将在其中输入货币值。我想要实现的是当用户输入时或者至少在他完成输入值之后,textfield还会显示与他所在地区相对应的货币符号。

它就像一个占位符,但不是我们在xcode中所拥有的那个,因为xcode是在我们键入之前存在的,而我想要的那个应该在打字时和之后。我可以使用带有货币的背景图片,但之后我无法本地化应用程序。

所以,如果有人能提供帮助,我将不胜感激。

提前致谢。

2 个答案:

答案 0 :(得分:5)

您必须使用NSNumberFormatter来实现此目标。

尝试以下代码,一旦您输入值并结束编辑,这些值将使用当前货币格式化。

-(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;
}

答案 1 :(得分:5)

最简单的方法是将带有右对齐文字的标签放在文字字段上,这样就会留下对齐的文字。

当用户开始编辑文本字段时,请设置货币符号:

    - (void)textFieldDidBeginEditing:(UITextField *)textField {
        self.currencyLabel.text = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
    }

如果你想把它作为textField中文本的一部分,它会变得有点复杂,因为你需要让它们一旦你把它放在那里就不能删除它:

// Set the currency symbol if the text field is blank when we start to edit.
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField.text.length  == 0)
    {
        textField.text = [[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol];
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString *newText = [textField.text stringByReplacingCharactersInRange:range withString:string];

    // Make sure that the currency symbol is always at the beginning of the string:
    if (![newText hasPrefix:[[NSLocale currentLocale] objectForKey:NSLocaleCurrencySymbol]])
    {
        return NO;
    }

    // Default:
    return YES;
}

正如@Aadhira指出的那样,您还应该使用数字格式化器格式化货币,因为您要将其显示给用户。