iOS监听tableView组头切换事件

2019-08-15  本文已影响0人  JxSr程知农

### 1、下面的函数是UITableViewDelegate的两个方法。

- (void)tableView:(UITableView*)tableView willDisplayHeaderView:(UIView*)view forSection:(NSInteger)section; *// 组头将要出现的时候系统会调用。*

- (void)tableView:(UITableView*)tableView didEndDisplayingHeaderView:(UIView*)view forSection:(NSInteger)section; *// 组头刚消失的时候系统会调用。*

利用以上两个方法可以判断出组头往上被顶出去或者组头又下拉回来的事件,还有其他的组头相关动作可以监听需自己去编写。

### 2、几个标记变量。

_currentSection:当前显示的组头。

_isUpScroll:是否是上拉滚动。

_oldY:滚动的偏移量。

### 3、相关的逻辑代码。

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section {

    if (!_isUpScroll && (_currentSection - section) == 1) {

       //上面的组头(不一定是第一个组头,而是指被顶出去的组头)又被拉回来。

       _currentSection = section;

        NSLog(@"willDisplayHeaderView显示第%ld组", (long)section);

    }

}

- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section {

    if (_isUpScroll) {

        _currentSection = section + 1;

        //最上面的组头被顶出去。

        NSLog(@"didEndDisplayingHeaderView显示第%ld组", (long)section + 1);

    }

}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    if (![scrollView isEqual: self.tableView]) {

        return;

    }

    if (self.tableView.contentOffset.y > _oldY) { 

        NSLog(@"上滑");

        _isUpScroll = YES;

    } else { 

        NSLog(@"下滑");

        _isUpScroll = NO;

    }

}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    // 获取开始拖拽之时tableview的偏移量。

    _oldY = self.tableView.contentOffset.y;

}

原文地址:  [https://www.cnblogs.com/piaojin/p/5945095.html](https://www.cnblogs.com/piaojin/p/5945095.html)  。

推荐文章:  [iOS - 30个Swift项目](https://www.jianshu.com/p/6cd4de45f004)  。
上一篇 下一篇

猜你喜欢

热点阅读