iOS设置tableViewCell之间的间距(去掉UItableview headerview黏性)

  经常在项目中遇到自定义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好用。因为间距比较好控制,不需要很繁琐的去计算。

posted @ 2015-05-19 12:33  6度XZ  阅读(7671)  评论(0编辑  收藏  举报