Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding keyboard when clear button is pressed in UITextField

Tags:

Is there any way to hide the keyboard when a clear button of UITextField is pressed?

like image 254
Naveed Rafi Avatar asked Jan 30 '11 16:01

Naveed Rafi


Video Answer


1 Answers

Yes, there is, although I suspect that doing so would violate the Apple Human Interface Guidelines.

To do so, add the following method to your view controller's implementation file. Then make the view controller into your textfield's delegate.

- (BOOL) textFieldShouldClear:(UITextField *)textField{     [textField resignFirstResponder];        return YES; } 

The downside to this approach is if you ever want to prevent the textfield from clearing, your code becomes messy. Instead you might try to define a custom method and then connect it to the valueDidChange method and check for an empty value.

-(IBAction)hideKeyboardFromTextField:(id)sender{   //TODO: Check if the previous value was longer than one character to differentiate   //between backspace and clear.     //check if the editing caused the box to be empty   if([[sender value] isEqualToString:@""] || [sender value] == nil)     [sender resignFirstResponder];   } } 

The problem here is that you can't easily differentiate between a tap on the clear button and a tap on the delete button when there is one character in the UITextField.

As I said in the beginning of my answer, this is not advisable in the first place and as the answers here have shown, it is not so easy to implement. I don't think it's worth the hassle, considering the difficulty involved and the fact that it doesn't result in optimal user experience.

like image 50
Moshe Avatar answered Oct 19 '22 01:10

Moshe