最简单的方法是将带有右对齐文本的标签放在您的文本字段上,该文本字段将具有左对齐文本。
当用户开始编辑文本字段时,设置货币符号:
- (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 指出的那样,您还应该使用数字格式化程序来格式化货币,因为您正在向用户显示它。