7

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

Thanks in advance!

WPK
  • 392
  • 3
  • 10

2 Answers2

13

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.

oren
  • 3,159
  • 18
  • 33
  • Well the code is correct, but there is no reason for lastY value because in every call it is set again ... – Skodik.o Jun 08 '15 at 11:46
  • 1
    @Skodik.o can you please explain what do you mean? The lastY is to know where was the scrollView last time, without it it will print "Header view just disappeared" on every scroll when it's not visible, you need to print it exactly when the header appears/disappears. It is static, it is set to 0 only for first time... – oren Jun 08 '15 at 15:48
  • tableView:didEndDisplayingHeaderView:forSection: doing will for me, thanks. – Fadi Abuzant Nov 08 '20 at 17:19
4

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
    }

}
Balazs Nemeth
  • 2,333
  • 19
  • 29