Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 235
Josh Knauer Avatar asked Mar 15 '11 18:03

Josh Knauer


3 Answers

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;
}
like image 159
Sig Avatar answered Nov 15 '22 12:11

Sig


Aaron answer works fine. A simpler way of doing things, by editing your peace of code:

NSString* searchText = self.searchDisplayController.searchBar.text;
[self.searchDisplayController setActive:NO animated:NO];
self.searchDisplayController.delegate = nil;
self.searchDisplayController.searchBar.text = searchText;
self.searchDisplayController.delegate = self; //or any delegate you like!

That way, none of your delegate functions are going to be triggered when setting the search bar text.

like image 39
Aurelien Porte Avatar answered Nov 15 '22 13:11

Aurelien Porte


In Apple's internal forum someone suggested a workaround of setting the placeholder text of the searchBar to the last search text when the UISearchDisplayController deactivates. It appears in the box, but it's greyed out. Not ideal, but possibly acceptable.

like image 27
Josh Knauer Avatar answered Nov 15 '22 12:11

Josh Knauer