Dismissing keyboard from UISearchBar when the X button is tapped

前端 未结 14 1277
眼角桃花
眼角桃花 2020-12-24 07:42

I\'m using the UISearchBar (but not the SearchDisplayController that\'s typically used in conjunction) and I\'d like to dismiss the keyboard when you hit the \'X\' button.

14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-24 08:31

    Toms answer got me thinking. If it is that the search bar is not yet the firstResponder when the user clicks the clear button we can just wait until it is, and then have it resignFirstResponder; i.e. along the lines of:

    - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
    {
      [self performFilteringBySearchText: searchText]; // or whatever
    
      // The user clicked the [X] button or otherwise cleared the text.
      if([searchText length] == 0) {
        [searchBar performSelector: @selector(resignFirstResponder) 
                        withObject: nil 
                        afterDelay: 0.1];
      }
    }
    

    Works like a charm, and less hacky than Tom's IMHO.

提交回复
热议问题