Search code examples
ios7uinavigationcontrolleruibarbuttonitemnsfetchedresultscontrolleruisearchdisplaycontroller

How to integrate UISearchDisplayController with a bar button item iOS 7


Until now I'm only familiar with one practice of UISearchDisplayController that integrating it with UISearchBar put on tableView. I see some apps when clicking bar button item it triggers UISearchDisplayController instead of touch on searchBar. Does anyone has any idea how to do it?


Solution

  • I have figured out a trick to do it by writing following code in 2 delegate methods of search bar

    - (void)searchButtonTapped:(id)sender
    {
       self.dictionaryTableView.tableHeaderView = _searchBar;
       [self.searchDC setActive:YES animated:YES];
       [self.searchDC.searchBar becomeFirstResponder];
    }
    
    - (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
    {
        [self.searchDC setActive:NO animated:YES];
        self.dictionaryTableView.tableHeaderView = nil;
    }
    

    The problem is UISearchDisplayController will not appear even setActive called if its search bar is not part of the view. Therefore, when button is tapped, I set searchBar to tableViewHeader, and activate searchdisplaycontroller. Then when the search is finished I inactivate searchdisplaycontroller, and set nil tableViewHeader to ensure the search bar won't show on the screen.