【问题标题】:Grouping separator while changing value in UITextfield在 UITextfield 中更改值时分组分隔符
【发布时间】:2013-06-25 14:53:36
【问题描述】:

为了编辑UITextField 中的分组分隔号码,需要在编辑时切换分组分隔符。否则返回的值(存储为NSNumber 值)是(NULL),由于错位的gouping 分隔符(参见图片并想象该数字将扩展另一个数字,例如“50.0000”)。

我怎样才能做到这一点?

现在该值在-(void) textFieldDidEndEditing:(UITextField *)textField 方法中处理。

(我的语言环境是德语,所以“.”是分组分隔符而不是小数分隔符!)但我尝试让代码适用于所有地区。

【问题讨论】:

    标签: ios uitextfield nsnumber


    【解决方案1】:

    感谢 thedjnivek 和他的第二个建议。我不得不稍微调整一下,现在它就像一个魅力。我的最终代码仅适用于所有有相同问题的人:

    -(void) textFieldDidEndEditing:(UITextField *)textField
    {
    
    NSMutableString* mstring = [[textField text] mutableCopy];
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc]init];
    [numberFormatter setLocale:[NSLocale currentLocale]];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    
    NSString* localeSeparator = [[NSLocale currentLocale]
                                 objectForKey:NSLocaleGroupingSeparator];
    NSNumber* number = [numberFormatter numberFromString:[mstring
                    stringByReplacingOccurrencesOfString:localeSeparator withString:@""]];
    
        [textField setText:[numberFormatter stringFromNumber:number]];        
    }
    

    【讨论】:

      【解决方案2】:

      试试这个解决方案:

      -(void) textFieldDidEndEditing:(UITextField *)textField {
      
       NSString *stringWithoutDots = [textField.text stringByReplacingOccurrencesOfString:@"." withString:@""]; //remove dots
      
      int number = [stringWithoutDots intValue]; //convert into int
      
      NSNumberFormatter *formatter = [NSNumberFormatter new];
      [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
      
      NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:number]];
      
      
      
      }
      

      希望对您有所帮助。 凯文·马查多

      【讨论】:

      • 感谢 thedjnivek,我会检查一下。给我一些时间。
      • 我不得不稍微调整一下,但你给了我一些很好的提示。谢谢你!
      【解决方案3】:

      你可以在这里看到答案:

      How to add commas to number every 3 digits in Objective C?

      不要自己格式化数字。你几乎肯定不会得到 所有边缘情况都正确或正确处理所有可能的语言环境。采用 用于将数字数据格式化为本地化的 NSNumberFormatter 字符串表示。

      您将使用 NSNumberFormatter 实例方法 -setGroupingSeparator:将分组分隔符设置为@"。" (或者更好的 [[NSLocale currentLocale] objectForKey:NSLocaleGroupingSeparator];谢谢@ntesler)和 -setGroupingSize:每隔 3 位放置一个分组分隔符。

      ++, 凯文·马查多

      【讨论】:

      • 感谢 thedjnivek,我使用 NSNumberFormatter 在文本字段中创建单独的输出。当文本字段中的已编辑(扩展)数字返回到(格式化)NSNumber 对象时,会出现此问题。如果数字被扩展,例如由于错位分组分隔符,返回值为一位数(NULL)。例如:文本字段显示“50.000”,用户在“50.0000”的末尾添加一个数字,现在返回时,文本不再作为组分隔数字对象返回。
      • 哦,好吧,对不起,我不明白:)
      • 感谢您的帮助!
      猜你喜欢
      • 1970-01-01
      • 2018-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 2014-01-10
      • 1970-01-01
      相关资源
      最近更新 更多