Action when the small cross button of UITextField is pressed

♀尐吖头ヾ 提交于 2019-12-01 07:06:28

问题


I can add a small cross button that is used to clear all the text in a single click in a UITextField with the following code.

textField.clearButtonMode = UITextFieldViewModeWhileEditing;

I also implemented UITextFieldDelegate.

I want to activate/deactivate the right bar button of the UINavigationBar according to the changes in my UITextField. The rule is simple: if the text field has at least one character, just enable the button, else disable it.

I implemented the UITextField's delegate method textField:shouldChangeCharactersInRange: to constantly check the requirement and update the status of the button.

Now my problem is, when I click the small cross button on the text field, the method textField:shouldChangeCharactersInRange: is not called. So the required action is missing. How can I identify the hit event of the clear button?

Some pictures to show what I'm talking about.

Initial stage: here, the "Done" button is disabled because there are no letters in the text field

When typing a letter, the "Done" button is enabled

Now, if I click on the clear button, the "Done" button is still enabled. This is wrong.


回答1:


Use the delegate method textViewShouldClear::

Asks the delegate if the text field’s current contents should be removed.

- (BOOL)textFieldShouldClear:(UITextField *)textField

Parameters

textField

The text field containing the text.

Return Value

YES if the text field’s contents should be cleared; otherwise, NO.

Discussion

The text field calls this method in response to the user pressing the built-in clear button. (This button is not shown by default but can be enabled by changing the value in the clearButtonMode property of the text field.) This method is also called when editing begins and the clearsOnBeginEditing property of the text field is set to YES.

Implementation of this method by the delegate is optional. If it is not present, the text is cleared as if this method had returned YES. Availability

* Available in iOS 2.0 and later.

Declared In UITextField.h




回答2:


You can use textFieldShouldClear: delegate method to handle when user taps on clear button.



来源:https://stackoverflow.com/questions/7304311/action-when-the-small-cross-button-of-uitextfield-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!