在某些情況下我們可能需要headerView跟隨cell滑動,而不是停留在頂部。要實現跟隨滑動,我總結了如下幾個方法
方法一:(特殊情況)
如果你的tableview恰好只有一個headerView,實現這種效果就好辦了。把要設置的headerView設置成tableView的header而不是section = 0的headerView。
方法二:
該方法比較簡單,設置tableView的style爲UITableViewStyleGrouped即可。代碼如下:
self.tableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen]bounds] style:UITableViewStyleGrouped];
方法三:
由於tableView是特殊的scrollView,在controller中加入如下代碼:
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
CGFloat sectionHeaderHeight = self.sectionHeight;
// NSLog(@"%f,%f",scrollView.contentOffset.x,scrollView.contentOffset.y);
if(scrollView == self.tableView){
if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>= -64) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}
}
其中sectionHeight爲你的tableview的section=0的headerView的高度。
由於我的tableViewController是在navigationController中使用的,而使用navigationController會使tableView(scrollView)的subView整體下移64,所以使用scrollView.contentOffset.y>=-64,如果沒有使用navigationController就應該使用scrollView.contentOffset.y>=-64。這個根據自己的情況設置就好了。
當然,你也可以將你的headerView自定義成tableViewCell,在section.row=0處展示,實現方式多種多樣,我只總結了這幾個中規中矩的方法,僅供參考。