【问题标题】:Changing iOS textfield on the fly to show currency即时更改 iOS 文本字段以显示货币
【发布时间】:2014-07-02 04:51:23
【问题描述】:

我有一个需要显示一些货币数据的UITextField。这个想法是它应该始终显示带有 $ 符号的格式化数字。

这是我目前使用的代码:

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



    [self performSelector:@selector(timeToSearchForStuff:) withObject:textField afterDelay:0.3];


    return YES;
}

- (void)timeToSearchForStuff:(UITextField*)textField
{
    if (textField.text.length == 0) {
        textField.text = @"$";
    }

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
        [numberFormatter setMaximumFractionDigits:0];
        [numberFormatter setMinimumFractionDigits:0];

    NSLocale *priceLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_AU"]  ;

    [numberFormatter setLocale:priceLocale];

    long long inuy =[[numberFormatter numberFromString:textField.text]integerValue];

    NSLog(@"starteo");

    NSLog(@"inuy :: %lld", inuy);

    NSString *formattedString =[numberFormatter stringFromNumber:[NSNumber numberWithLong:inuy]];

    NSLog(@"chupacabra3 :: %@", formattedString);

    self.textField.text = formattedString;

}

这在我输入超过 4 位数字之前都可以正常工作,如果我输入第 5 位数字,则文本字段会变为零。

如果我只是记录该值,它会执行正常,但如果我将文本设置在第 5 位,它会再次变为零。

需要一些帮助来解决这里出了什么问题。指引我正确的方向。

谢谢。

【问题讨论】:

    标签: ios uitextfield


    【解决方案1】:

    改变这个条件

    if (textField.text.length == 0) {
        textField.text = @"$";
    }
    

    有了这个

    if (textField.text.length == 0) {
        textField.text = @"$";
    } else {
        [textField setText:[textField.text stringByReplacingOccurrencesOfString:@"," withString:@""]];
    }
    

    【讨论】:

      猜你喜欢
      • 2013-07-03
      • 2023-04-03
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多