Toggle SearchBar in iOS
-
22-02-2021 - |
Frage
I have a TableView
along with a search button at the bottom. I would like for the search button to cause a SearchBar
to pop in at the top and be brought into focus. Otherwise, there should be no SearchBar
showing.
It's easy enough to put a search bar above the TableView
, but is there a way to hide/show it with animation?
Thanks.
Lösung
Have you tried using the -[UITableView scrollRectToVisible:animated:]
method? I think the UISearchBar
view is usually just a header view on the table, so you should be able to ask the table view to scroll up to show the search bar.
Andere Tipps
This works for me. Hope it helps.
Call [self hideSearchBar] in your viewWillAppear (this will hide the search bar initially).
Your search button should have the following action:
- (IBAction)searchIconButtonClicked {
if (self.searchDisplayController.isActive || (self.tableView.contentOffset.y < 44)) {
if (self.searchDisplayController.isActive) {
self.searchDisplayController.searchBar.text = nil;
[self.searchDisplayController setActive:NO animated:YES];
[tableView reloadData];
}
[self hideSearchBar];
} else {
[self.patientTableView scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:YES];
}
}
- (void)hideSearchBar {
//NSLog(@"Hiding SearchBar");
[self.tableView setContentOffset:CGPointMake(0,44)];
}