0

I cant seem to find this answer for the manually clearing the UISearchBar with a backspace, only with a cancel button click. The code below hides the keyboard when the clear button is clicked, but so does the backspace to an empty UISearchBar. Id like to leave the keyboard open in that scenario since someone might be typing something else.

-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
    [self filterData: text];

    if(text.length == 0)
    {
        [searchBar performSelector:@selector(resignFirstResponder) withObject:nil afterDelay:.1];
    }
}
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341

3 Answers3

0

Your code includes if(text.length == 0) and that means that when the size of the input becomes zero, keyboard is dismissed. However the actual piece should be as follows:

- (BOOL) searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    return YES;
}
Keshav
  • 1,123
  • 1
  • 18
  • 36
0

My best try on such an issue is to do as suggested here BUT IT DOES NOT WORK WHEN YOU CLICK CLEAR BUTTON :( but I thought it might help you though: https://stackoverflow.com/a/16957073/1465756

Add a tap gesture on your whole view:

 - (void)viewDidLoad
{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
                               initWithTarget:self
                               action:@selector(dismissKeyboard)];

[self.view addGestureRecognizer:tap];
}

and dismissKeyboard when the view is tapped:

  - (void) dismissKeyboard
{
  [self.searchBar resignFirstResponder];
}
arniotaki
  • 2,175
  • 2
  • 23
  • 26
-1

I understand you want to dismiss the keyboard when the user hits Cancel, and you also want to dismiss when the user hits the clear (x) button.

You do not need to implement searchBar:textDidChange:.

To detect cancellation, implement searchBarCancelButtonClicked:. Here you can trigger resignFirstResponder.

To detect clear, adopt UITextFieldDelegate and implement textFieldShouldClear:. This will be called after the user taps clear, but before the clear occurs. Return YES to allow the clear to occur. You may dismiss the keyboard before returning.

Jordan H
  • 52,571
  • 37
  • 201
  • 351
  • Cancel ONLY works with the Cancel button, this is the clear button, they are totally different. – Mike Flynn Dec 27 '15 at 21:27
  • Your question is not related to the Cancel button then? You want to resign when they hit the clear button instead? Please update your question - you only mention the cancel button not clear. – Jordan H Dec 27 '15 at 21:48
  • "Hide Keyboard on clear click in UISearchBar and not backspace to empty text" – Mike Flynn Dec 28 '15 at 02:46