当用户在UITextField中输入值时,如何添加货币分隔符或货币面额

时间:2017-01-18 11:15:16

标签: ios objective-c string uitextfield

这里有点混乱。我只想在用户输入值时添加货币分隔符,并在用户编辑该值时调整分隔符位置。我在此尝试了它但它只处理最近输入的字符

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text

如果有人知道任何更好的委托方法,那么请....

1 个答案:

答案 0 :(得分:0)

检查以下代码,可能会根据您的要求提供帮助和更改:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text{

   NSDecimalNumber *amount = [NSDecimalNumber decimalNumberWithString: textField.text];

   NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];

   [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
   NSString *formattedCurrency = [currencyFormatter stringFromNumber:amount];

   if ([formattedCurrency isEqualToString:@"NaN"]) {

       formattedCurrency=@"";
   }
   textField.text=[NSString stringWithFormat:@"%@",formattedCurrency];

   return YES;

}