在我的应用程序中,用户在一个视图中有多个输入字段用于货币值。因此,根据区域设置,字段中的值应显示为“$ 5.00”。这行得通。
为了编辑字段,我基本上在用户输入值时“取消本地化”字符串并删除货币符号。编辑后的值应保存(当然也没有货币符号)到核心数据中。由于所有字段都需要以不同的方式保存到数据库中,因此我必须遍历所有字段并覆盖所有核心数据值。所以我必须“取消本地化”我视图的所有字段才能保存它们。这适用于除已编辑的文本字段之外的所有文本字段。如果我将这个已经未本地化的值发送到我的方法,它只会返回 0。为什么?
我的视图控制器的两种方法:
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"Done", nil) style:UIBarButtonItemStyleDone target:self action:@selector(doneEditing:)];
[self.navigationBar setRightBarButtonItem:doneButton];
if(textField.tag != 1){
//1 is the name text field
textField.text = [NSString stringWithFormat:@"%.2f",[NSNumber getUnLocalizedCurrencyDoubleWithString:textField.text]];
}
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
self.spendingCategory.name = self.nameTextField.text;
self.spendingCategory.costPerDay = [NSNumber numberWithDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.dailyTextField.text]];
self.spendingCategory.costPerWeek = [NSNumber numberWithDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.weeklyTextField.text]];
self.spendingCategory.costPerMonth = [NSNumber numberWithDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.monthlyTextField.text]];
self.spendingCategory.costPerSemiYear = [NSNumber numberWithDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.semiAnnuallyTextField.text]];
self.spendingCategory.costPerYear = [NSNumber numberWithDouble:[NSNumber getUnLocalizedCurrencyDoubleWithString:self.annuallyTextField.text]];
[self setTextFieldsWithFormat];
}
还有我的 NSNumber 类别:
- (NSString *) getLocalizedCurrencyString
{
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
NSString *numberString = [numberFormatter stringFromNumber:self];
return numberString;
}
+ (double) getUnLocalizedCurrencyDoubleWithString:(NSString *)currencyString
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
return [[numberFormatter numberFromString:currencyString] doubleValue];
}