How to detect when a UITableView header is scrolle

2019-02-19 03:18发布

问题:

How to detect when a UITableView header (table header, not section header) is scrolled off visible area?

Thanks in advance!

回答1:

There are couple of possible solutions I can think of:

1) You can use this delegate's method:

tableView:didEndDisplayingHeaderView:forSection:

However, this method is called only if you provide header in the method

tableView:viewForHeaderInSection:

You said 'not section header', but you can use the first section header in a grouped tableView as the table headerView. (The grouped is for the header will scroll together with the table view)

2) If you don't want to use grouped tableView and the section header, you can use the scrollView's delegate (UITableViewDelegate conforms to UIScrollViewDelegate). Just check when the tableView is scrolled enough for disappearing the tableHeaderView. See the following code:

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

    static CGFloat lastY = 0;

    CGFloat currentY = scrollView.contentOffset.y;
    CGFloat headerHeight = self.headerView.frame.size.height;

    if ((lastY <= headerHeight) && (currentY > headerHeight)) {
        NSLog(@" ******* Header view just disappeared");
    }

    if ((lastY > headerHeight) && (currentY <= headerHeight)) {
        NSLog(@" ******* Header view just appeared");
    }

    lastY = currentY;
}

Hope it helps.



回答2:

Here is how a tableView can specify itself whether its tableViewHeader is visible or not (Swift 3):

extension UITableView{

    var isTableHeaderViewVisible: Bool {
        guard let tableHeaderView = tableHeaderView else {
            return false
        }

        let currentYOffset = self.contentOffset.y;
        let headerHeight = tableHeaderView.frame.size.height;

        return currentYOffset < headerHeight
    }

}