2012-11-22 71 views
8

我有我的工作,这股市场计算器和我搜索苹果文档,上网,在这里StackOverflow上,但没有成功地找到了答案..如何在UITextfield中输入时输入货币符号?

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

这就像一个占位符,而不是一个我们在Xcode,导致Xcode的是有我们之前输入和一个我想应该有打字时和之后。我可以使用带有货币的背景图片,但之后我无法本地化应用程序。

因此,如果任何人能帮助,我将不胜感激。

在此先感谢。

+0

你说的“Xcode的货币符号”是什么意思? – 2012-11-25 14:06:31

回答

5

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

当用户开始编辑的文本框,设置货币符号:

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

如果你想保持它作为文本框的文本部分,就显得有点复杂,因为你需要让他们从删除符号,一旦你把它放在那里:

// 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指出的那样,你也应该用一个数字格式化,因为你是它向用户显示格式化的货币。

3

你必须使用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; 
} 
相关问题