也适用于 UITableViewStyleGrouped 的更简单的方法(另外不需要更改行数)是为contentInset
表格设置动画:
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;
}];
}
我知道这是在 OP 提出问题三年后,但由于这是实现预期效果的好选择,我认为它可能对其他遇到相同问题的人有用。