让tableView的每个section的headerview随tableview一行滚动

让tableView的每个section的headerview随tableview一起滚动

如何让 UITableView 的 headerView跟随 cell一起滚动

UITableView 的 headerView一般是随着tableView的滚动悬浮在cell上的,但是有时候我们并不希望它是悬浮的状态,那么就要让headerView能够跟随cell一起滚动。之前只有自己用用,并没有做过总结,昨天有朋友问该怎么解决我就搜索了一下这个问题,发现解决方案并不止一种,对于section只有一个的情况,我个人一直用的是方案3,也比较推荐这个方法,很简单。在我的代码中,我初始化了一个自定义的headerImageView,通过代码

myTable.tableHeaderView =headerImageView;
将我的headerImageView给了tableview的headerView,这样就成功达到了想要的效果。

在这里进行总结备忘,方便以后查阅,也希望对用到此文的人有所帮助。


解决方案1:(适用于多个section的情况)

//去掉UITableView headerView黏性  要将tableview的style设置为UITableViewStyleGrouped

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {  
    if (scrollView == self.myTableView)  
    {  
        CGFloat sectionHeaderHeight = YOUR_HEIGHT;  
        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);  
        }  
    }  
}


[原帖地址:http://www.cocoachina.com/bbs/read.php?tid-86162-page-1.html]


解决方案2:

设置 tableView的 style为  UITableViewStyleGrouped,然后

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}

      这样确实可以让 headerView ,在滚动tableView的时候,跟随着cell的内容一起滚动。但是,下面的cell都被加上了边框 而且cell的水平显示范围变窄了。

解决方案3(!!!!推荐):

将UIView设置为  整个tableView的headerView,而不是 section 0的headerView

  self.tableView.tableHeaderView=header;

  这样,就可以完美的满足 headerView跟随cell的内容一起滚动的要求。

[原帖地址:http://blog.csdn.net/tangaowen/article/details/6452314]



解决footerView黏性的问题待整理





版权声明:本文为博主原创文章,未经博主允许不得转载。