My app uses an UISearchDisplayController
. When the user has entered a search term I want it to remain visible in the searchbar. This works if the user chooses one of the matched results, but not if the user clicks the 'Search' button.
This works:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (tableView == self.searchDisplayController.searchResultsTableView) {
NSString *selectedMatch = [self.searchMatches objectAtIndex:indexPath.row];
[self.searchDisplayController setActive:NO animated:YES];
[self.searchDisplayController.searchBar setText:selectedMatch];
return;
}
...
But if I do the same thing in -searchBarSearchButtonClicked:
the text doesn't remain in the searchbar. Any ideas on how I can accomplish this in this situation?
Related, if I set the text of the searchbar (but leave the UISearchDisplayController
inactive) this triggers the display of the searchResultsTableView. I only want to show that when the user taps on the searchbar.
Edit: Found a workaround to set the text of a searchbar without showing the searchResultsTableView at any time:
// This hacky YES NO is to keep results table view hidden (animation required) when setting search bar text
[self.searchDisplayController setActive:YES animated:YES];
[self.searchDisplayController setActive:NO animated:YES];
self.searchDisplayController.searchBar.text = @"text to show";
Better suggestions still welcomed!
Actually you cannot use the same code inside the searchBarSearchButtonClicked method because you have no indexPath to select the right element in your searchMatches array.
If the user clicks the search button and you want to hide the searchController interface you have to figure out what text to put inside the search (for example selecting the best matching result in the list).
This example just let the search term remain visible and unchanged when the user clicks the search button :
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString *str = searchBar.text;
[self.searchController setActive:NO animated:YES];
self.searchController.searchBar.text = str;
}
Hope this helps, Vincent
Resetting manually the string in the search bar triggers some of the UISearchDisplayDelegate methods again. This is something you probably don't want, in this case.
I would modify vdaubry answer a bit, and it gives me:
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSString *str = searchBar.text;
[self.searchController setActive:NO animated:YES];
self.searchController.delegate = nil;
self.searchController.searchBar.text = str;
self.searchController.delegate = self //or put your delegate here if it's not self!
}
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