I have a subclass of UITableViewController. I have code that can add/remove a UISearchBar to/from the tableHeaderView of my tableView. Here's the code I have to perform these tasks:
self.tableView.tableHeaderView = uiSearchBar; //Make the search bar appear
self.tableView.tableHeaderView = nil; //Make the search bar disappear
The problem is that I want the adding/removing of the UISearchBar to be animated; slide into view from the top when I add it then slide upwards and out of view when I remove it instead of just appearing and disappearing. Any suggestions?
Thanks.
I was finally able to figure this out. Turned out to be pretty simple. Instead of adding the UISearchBar to the table header, I insert it into the first cell of the table with animation UITableViewRowAnimationTop and remove it using the same method. This results in the bar sliding in and out from the top. Here is the code that makes the bar appear:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.baseUiTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
[self.baseUiTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
And here is the code that removes the search bar:
[uiSearchBar resignFirstResponder];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.baseUiTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationTop];
A much simpler way that is also suitable for UITableViewStyleGrouped (plus doesn't require changing the number of rows) is to animate the contentInset
of the table:
CGFloat h = uiSearchBar.bounds.size.height;
UITableView *tv = self.tableView;
if (tv.tableHeaderView)
{ // hide bar
[UIView animateWithDuration:0.3 animations:^{
tv.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0);
} completion:^(BOOL finished) {
tv.contentInset = UIEdgeInsetsZero;
tv.tableHeaderView = nil;
[tv scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}];
}
else
{ // show bar
uiSearchBar.frame = CGRectMake(0, -h, tv.frame.size.width, h);
[UIView animateWithDuration:0.3 animations:^{
[tv scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
tv.tableHeaderView = uiSearchBar;
}];
}
I know this is three years after the OP asked the question, but since this is a good alternative to achieve the desired effect, I thought it might be useful for others meeting the same problem.
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