【问题标题】:Having trouble with currency货币问题
【发布时间】:2015-06-10 05:12:41
【问题描述】:

我有一个UITextField,用户将输入金额。我想设置它,以便向用户显示当前货币。

这是我的项目的链接。它给了我奇怪的结果:jumpShare

【问题讨论】:

标签: ios objective-c uitextfield


【解决方案1】:

实际上,您已尝试在开始时设置小数部分,因此它可以赚到 1.00 美元这样的金额。所以你不能在UITextField 中添加更多数字。所以删除了那个东西。添加更多修改,如下所示。

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

    if (![string isEqualToString:@""]) {

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{



            NSNumberFormatter *currencyFormatter = [[NSNumberFormatter alloc] init];
            [currencyFormatter setLocale:[NSLocale currentLocale]];
            [currencyFormatter setMaximumFractionDigits:0];
            [currencyFormatter setAlwaysShowsDecimalSeparator:NO];
            [currencyFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

            textField.text = [textField.text stringByReplacingOccurrencesOfString:currencyFormatter.currencySymbol withString:@""];

            NSCharacterSet *nonNumbersSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];

            textField.text = [textField.text stringByTrimmingCharactersInSet:nonNumbersSet];


            NSNumber *someAmount = [NSNumber numberWithUnsignedInteger:[[textField.text stringByReplacingOccurrencesOfString:@"," withString:@""] longLongValue]];
            NSString *t = [currencyFormatter stringFromNumber:someAmount];
            self.textField.text = t;



        });
    }

    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{

    return YES;
}

替换这两种方法,可以解决你的问题。

【讨论】:

  • 谢谢!!更好,但我现在不能添加小数,而且当我退格时会产生奇怪的效果 - 删除字符
  • @Eric,当你退格时会发生什么。
  • 有些字符不退格。如果您愿意,可以在 questin 中发布的项目中尝试一下
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多