How do you dynamically format a number to have commas in a UITextField entry?

前端 未结 9 2086
傲寒
傲寒 2020-12-08 17:42

I want to have commas dynamically added to my numeric UITextField entry while the user is typing.

For example: 123,456 and 12,345,678

9条回答
  •  孤街浪徒
    2020-12-08 17:54

    Windy please keep in mind the commas should get add to the number itself, not like user has to enter them.

    First

    // Add a "textFieldDidChange" notification method to the text field control.
    [textField addTarget:self 
              action:@selector(textFieldDidChange:) 
    forControlEvents:UIControlEventEditingChanged];
    

    You have to change to change the Text yourself. And the Code that will add the commas is

    -(void) textFieldDidChange {
    
        NSNumberFormatter *formatter = [NSNumberFormatter new];
        [formatter setNumberStyle:NSNumberFormatterDecimalStyle]; // this line is important!
    
        NSString *formatted = [formatter stringFromNumber:[NSNumber numberWithInteger:2000000]];
        NSLog(@"the Formatted String is  %@",formatted);
    
       textField.text = formatted;
    }
    

提交回复
热议问题