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?
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;
}
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With