經常在項目中遇到自定義cell的情況,而且要求cell之間有間距,但是系統沒有提供改變cell間距的方法,怎么辦?
方法1:自定義cell的時候加一個背景View,使其距離contentView的上下一定距離,實際上cell之間沒有間距,但是顯示效果會有間距。這個方法有個弊端,比如你設置的間距gap = 12;那么第一個cell距離上面距離為gap,而每個cell的間距為2*gap,效果不是很滿意。
方法2:創建tableView的時候用grouped,一個cell就是一個section。然后設置每個section的headView。
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 12; } -(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIUtils screenWidth], 12)]; headerView.backgroundColor = [UIColor backGroundGrayColor]; return headerView; }
可以看到每個cell的間距都一樣。但是問題來了,tableview的headview有粘性,會保持在tableView的頂部,我們只需要去除tableView的粘性就可以了。代碼如下
//去掉UItableview headerview黏性 - (void)scrollViewDidScroll:(UIScrollView *)scrollView { if (scrollView == self.tableView) { CGFloat sectionHeaderHeight = 12; 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); } } }
方法二2比方法1好用。因為間距比較好控制,不需要很繁瑣的去計算。
