【iOS 1 行代码系列】之 一行代码搞定TableView组头
2018-05-16 本文已影响63人
豪冷
场景:
当 UITableView 的 style 属性设置为 Plain 时
tableview 的 section header 在滚动到界面顶端时
会 悬停 !
疑问:
1.如何在不使用Grouped时,让组头不悬停??
2.如何在不重写-scrollViewDidScroll: (示例) 方法时,让组头不悬停???
办法:
1.针对没有内容的 section header
直接设置 header view 的背景颜色为 clearColor
设置 tableview 的背景颜色为 section header 的背景颜色
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
UIView *view = [[UIView alloc] init];
view.frame = CGRectMake(0, 0, kScreenWidth, 10);
view.backgroundColor = [UIColor clearColor];
return view;
}
2.针对有内容的 section header
- 使用
Grouped - 参考 示例
示例无法查看,请看以下原文(来自:https://www.jianshu.com/p/333f361ada36)
当 UITableView 的 style 属性设置为 Plain 时,这个tableview的section header在滚动时会默认悬停在界面顶端。取消这一特性的方法有两种:
1、将 style 设置为 Grouped 。这时所有的section header都会随着scrollview滚动了。不过 grouped 和 plain 的样式有轻微区别,切换样式后也许需要重新调整UI
2、重载scrollview的delegate方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat sectionHeaderHeight = 40;
if (scrollView.contentOffset.y<=sectionHeaderHeight&&scrollView.contentOffset.y>=0) {
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
} else if (scrollView.contentOffset.y>=sectionHeaderHeight) {
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, 0, 0);
}
}