UITableViewStyle有兩個選項:UITableViewStylePlain和UITableViewStyleGrouped。
contentInset:scrollview的contentView(即滾動的那部分view,以下都以這個簡稱)的頂點相對于scrollview的位置,例如你的contentInset = (0 ,100),那么你的contentview就是從scrollview的(0 ,100)開始顯示
Plain模式
Plain的效果如圖:(灰色底是tableView的父view,藍色底是tableView,下同)
上圖是sectionHeader和sectionFooter高度設置為20的情況。為了方便,下文直接用header和footer來表示。
- header默認會固定在tableView的頂部,因為彈動效果而改變位置;
- footer默認會固定在tableView的底部(數據不夠時,會緊跟著cell),因為彈動效果而改變位置。
假設你做了如下設置,那么最后一個cell的分割線會沒掉。就同我上圖一樣,設置了footerHeight后,系統會以為底部有內容,所以最后一個cell的分割線不會給出來。返回0.01其實也是有內容在的,只不過我們眼睛看不出來而已。
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0.01;
}
當tableView的contentInset設置為UIEdgeInsetsMake(10, 0, 10, 0),如下圖所示
- 可以看出header和footer不再固定在tableView的頭部和底部,而是偏移了10個像素點。
- 由于這個間隙,導致contentView滾動的內容會出現在這部分的間隙中。
但當tableView的contentInset設置為UIEdgeInsetsMake(-20, 0, -20, 0),如下圖
這兩張圖可以看出,無論inset怎么設置,header和footer都是contentView的頭部和底部。只要header和footer是處于屏幕顯示內的,那么就只有當滾動內容到頭/尾了,才會跟著滾動滾動。而如果處于屏幕之外的,就一定是緊跟著滾動內容。
于是乎,網友提出了這樣一個方法來讓Plain模式下的header和footer不固定在頭部和底部
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
CGFloat sectionHeaderHeight = 40;
CGFloat sectionFooterHeight = 10;
CGFloat offsetY = scrollView.contentOffset.y;
if (offsetY >= 0 && offsetY <= sectionHeaderHeight)
{
scrollView.contentInset = UIEdgeInsetsMake(-offsetY, 0, -sectionFooterHeight, 0);
}else if (offsetY >= sectionHeaderHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight)
{
scrollView.contentInset = UIEdgeInsetsMake(-sectionHeaderHeight, 0, -sectionFooterHeight, 0);
}else if (offsetY >= scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight && offsetY <= scrollView.contentSize.height - scrollView.frame.size.height)
{
scrollView.contentInset = UIEdgeInsetsMake(-offsetY, 0, -(scrollView.contentSize.height - scrollView.frame.size.height - sectionFooterHeight), 0);
}
}
Grouped模式
Grouped的效果如圖:
- header和footer就是contentView對應view的頭部和尾部。
很多人在使用Grouped模式時,會遇到一個問題,就是tableView的頂部和底部都會留白,這里說下我收集到的處理方法。
- self.automaticallyAdjustsScrollViewInsets = NO在控制器設置
- tableView.tableFooterView = [[UIView alloc] init]切記這段必須要放在tableView的兩個代理設置之后(我也才是抄來的)
但是,請記住,不管是上面的哪個方法,必須配合設置以下兩個方法才能去掉兩個留白部分。
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
return 0.01;
}
當tableView的contentInset設置為UIEdgeInsetsMake(10, 0, 10, 0),如下圖所示
有沒有一種很像contentOffset偏移的感覺
更新2017-05-25
樓主最近又發現了tableView使用UITableViewStyleGrouped底部會留空,百般嘗試后沒法子,直接用self.tableView.contentInset = UIEdgeInsetsMake(0, 0, -20, 0);呵呵噠...