WPK WPK - 1 month ago 14
iOS Question

How to detect when a UITableView header is scrolled off visible area?

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

Thanks in advance!

Answer

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.