Search code examples
iphoneiosuisearchdisplaycontroller

How to set text in UISearchBar without activating UISearchDisplayController


I'm using a UISearchDisplayController in my app. When the user selects an item in the search results returned I deactivate the UISearchDisplayController. Deactivating the controller clears the text the user has typed. I want to keep it there. I can force the text back into the UISearchBar by setting it again after the controller has been deactivated.

Like so:

NSString* searchText = self.searchDisplayController.searchBar.text;
[self.searchDisplayController setActive:NO animated:YES];
self.searchDisplayController.searchBar.text = searchText;

Which works.

However, I am seeing a timing issue if I don't animate the deactivate call. Calling setActive like so:

NSString* searchText = self.searchDisplayController.searchBar.text;
[self.searchDisplayController setActive:NO animated:NO];
self.searchDisplayController.searchBar.text = searchText;

causes the UISearchDisplayController to become active again!

Is there are a way that I can set the text of the UISearchBar without having the UISearchDisplayController that's associated with become active? Any other suggestions to get around this behaviour?


Solution

  • For any one else wondering how to do this I managed to get it working by adding this in my delegate:

    - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
    {
        if(!controller.isActive){
            controller.searchResultsTableView.hidden = YES;
            return NO;
        }
        controller.searchResultsTableView.hidden = NO;
    
        [....]
    
        return YES;
    }