How to Test Character Input to UITextField as the User Enters Characters and Prevent Invalid Characters

前端 未结 6 1916
深忆病人
深忆病人 2020-12-02 16:22

First, I setup up the keyboard for the UITextField to use the number with decimal style. So the user can only enter numbers and a single decimal.

What I want to do i

6条回答
  •  攒了一身酷
    2020-12-02 16:49

    The standard way of dealing with this issue in iOS is attaching a UITextFieldDelegate to your UITextField, and implement textField:shouldChangeCharactersInRange:replacementString: method. Inside this method you can validate the string to be of the correct "shape" for your purposes (one dot, no more than two digits after the dot, etc.) and supply a different string if the input does not follow the expected format.

提交回复
热议问题