Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 751
WPK Avatar asked Jan 09 '15 17:01

WPK


2 Answers

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.

like image 149
oren Avatar answered Nov 07 '22 15:11

oren


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
    }

}
like image 42
Balazs Nemeth Avatar answered Nov 07 '22 16:11

Balazs Nemeth