UITextFieldDelegate vs UITextField control events

后端 未结 5 814
隐瞒了意图╮
隐瞒了意图╮ 2021-02-14 08:17

If I want to handle changes to a UITextField, such as the user typing in it; it seems like this can be done either by assigning a delegate to that text field, and then having th

5条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 09:00

    shouldChangeCharactersInRange is called before a change occurs, and gives you opportunity to 'cancel' the change. UIControlEventEditingChanged is called after the change occurred.

    You can determine the resulting value of the textField in shouldChangeCharactersInRange, but you have to manually apply the replacementString to the existing text, using the supplied range. (via NSString stringByReplacingCharactersInRange). If you want to know the resulting text, it's easier and more efficient to use UIControlEventEditingChanged.

    shouldChangeCharactersInRange is often used to implement validation checking of input - that is, you can filter characters/pasted text as it is entered. If a field is for phone numbers, for example, you can return FALSE if the user types a non numeric character, or attempts to paste in text that isn't numeric.

    You might find a case where you can reuse code for multiple controls if you can stick with the UIControlEvent-methods.

提交回复
热议问题