美文网首页
iOS监听tableView组头切换事件

iOS监听tableView组头切换事件

作者: JxSr程知农 | 来源:发表于2019-08-15 11:15 被阅读0次
    
    ### 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)  。
    

    相关文章

      网友评论

          本文标题:iOS监听tableView组头切换事件

          本文链接:https://www.haomeiwen.com/subject/zjgajctx.html