【技巧】UITableView 在UITableViewStylePlain模型下,取消headerView的黏结性,不浮动

来源:互联网 发布:php warning 编辑:程序博客网 时间:2024/04/30 02:50
        UITableView使用UITableViewStylePlain样式时,section的header与footer会在滚动过程中固定在顶部,这个交互很不错。如果要阻止这个交互,那么办法有几个:
1. 样式改成UITableViewStyleGrouped,但是在iOS6上需要做很多样式调整才能达到与UITableViewStylePlain一致;
2. 每个section多加行来模拟header或footer,但是代码维护难度更大;
3. 继承UITableView,覆盖方法-allowsHeaderViewsToFloat或-allowsFooterViewsToFloat,但是使用了私有API审核有风险;
4. 自定义header或者footer阻止浮动, 重写tableview的frame
5. 假装cell为header。

        以上种种方法带有破坏性,入侵性:动不动修改frame和contentInset。现在介绍一个巧妙方法,使用简单。

设计思路:

        普通的section,cell多的话滑动时候超过一屏的高度,绿色的header会停留在section的top并浮动。如图1:


       那么如果section中的cell为空,它是不会浮动的;基于这个原理,可以巧妙的将header单独拎出来。如图2:试想分拆后的每一个section,只有第一个带有header,且不会浮动。为了扩展性,将footer也算进去。


        一图省千语啊

UITableViewDelegate UITableViewDataSource

将原始的section数量乘以3,得到header的section,cell的section,footer的section。

#pragma mark —————header——————- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {    if (section%3 == 0) {        /*正常的header 高度*/        return headerHeight;    }    return 0;}- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {    if (section%3 == 0) {        /*正常的header*/        return headerView;        }        return nil;}#pragma mark —————cell——————- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {    if (section%3 == 1) {        /*正常的cell 高度*/        return cellHeight;        }    return 0;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {    if (section%3 == 1) {        /*正常的cell*/        return cell;        }    return nil;}#pragma mark —————footer——————- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{    if (section%3 == 2) {        /*正常的footer 高度*/        return footerHeight;        }    return 0;}- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {    if (section%3 == 2) {        /*正常的footer*/        return footerView;        }    return nil;}

(完)

1 0
原创粉丝点击