Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

resignFirstResponder not getting called inside textFieldShouldClear

I am trying to implement search bar in one of my page.

I am not using regular search bar due to its design.

What I have is as below.

UIImageView above UIView (textfield background)
UITextField above UIImageView (textfield)

I am using delegates for UITextField.

In code I have searchTF.clearButtonMode = UITextFieldViewModeWhileEditing; to show the clear button.

Search is working fine but the problem is in delegate of clear button.

I have below code

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == searchTF) {

        NSLog(@"clicked clear button");
        [textField resignFirstResponder]; // this is not working
        // also below is not working
        // [searchTF resignFirstResponder];
    }

    return YES;
}

When I click clear button, I get NSLog of text "clicked clear button", however the keyboard doesn't get dismissed.

Any idea why keyboard is not getting dismissed when I have


Edit 1

Even I tried as below using [self.view endEditing:YES];, but still its not working.

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField == searchTF) {
        [self.view endEditing:YES];
        [self hideAllKeyboards];
    }
    return YES;
}
like image 605
Fahim Parkar Avatar asked Jan 17 '26 21:01

Fahim Parkar


1 Answers

Additional to my comment I made some testing and here are my results:

I've just implemented a UITextField with all delegate methods like this:

- (BOOL)textFieldShouldClear:(UITextField *)textField {
  NSLog(@"Should Clear");
  [textField resignFirstResponder];
  return YES;
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
  NSLog(@"Begin editing");
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
  NSLog(@"End editing");
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
  NSLog(@"Should begin editing");
  return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
  NSLog(@"Should end editing");
  return YES;
}

- (BOOL)textField:(UITextField *)textField
    shouldChangeCharactersInRange:(NSRange)range
                replacementString:(NSString *)string {
  NSLog(@"Change char");
  return YES;
}

As soon as you hit the clear button the log outputs:

2014-07-26 11:08:44.558 Test[36330:60b] Should Clear
2014-07-26 11:08:44.558 Test[36330:60b] Should end editing
2014-07-26 11:08:44.559 Test[36330:60b] End editing
2014-07-26 11:08:44.560 Test[36330:60b] Should begin editing
2014-07-26 11:08:44.561 Test[36330:60b] Begin editing

As you can see the shouldBeginEditingand the didBeginEditing methods get called after clearing so the resignFirstResponder in textFieldshouldClear gets called just before a new becomeFirstResponder is called by shouldBeginEditing or didBeginEditing.

like image 177
dibi Avatar answered Jan 20 '26 13:01

dibi