遇到货币问题

时间:2015-06-10 05:12:41

标签: ios objective-c uitextfield

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

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

1 个答案:

答案 0 :(得分:0)

实际上你已经尝试在开头设置小数分数,所以它的价格会达到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;
}

替换这两种方法,这可能解决了您的问题。