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

Mar*_*ida 9 currency objective-c uitextfield ios ios5

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

我有一个UITextfield用户将输入货币值.我想要实现的是当用户键入时或者至少在他完成输入值之后,文本字段还将显示与他所在的语言环境相对应的货币符号.

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

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

提前致谢.

Ila*_*ian 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;
}
Run Code Online (Sandbox Code Playgroud)


lna*_*ger 5

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

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

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

如果你想把它作为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;
}
Run Code Online (Sandbox Code Playgroud)

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