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

前端 未结 9 2032
傲寒
傲寒 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 18:05

    Use the UITextFieldDelegate method: (your view controller needs to be a delegate of the textfield)

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

    When a character is added to the textField, it will call this method. You can then insert commas wherever you want.

    Note: people can paste text into textfields, delete values, move the cursor, etc. so you have a lot of tests to consider.

    There are lots of similar questions on SO, e.g. How to put comma and decimals in my UITextField dynamically?

    Auto suggest in UITextfield with comma separation

    etc

提交回复
热议问题