Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when UITableView section header snaps to the top of the screen

I want to detect when the UITableView section header snaps on top of the screen and then modify header's height, but I have no idea how to do that. Can anyone help?

like image 980
Pakpoom Thaweesitthichat Avatar asked Jan 16 '17 05:01

Pakpoom Thaweesitthichat


1 Answers

I was able to accomplish detecting which header is stuck to top of the table view by using the didEndDisplayingHeaderView and willDisplayHeaderView delegate methods. The idea here is that the while we are scrolling through the sections of the table view, the rows around the header are becoming visible and we can grab the index paths of all visible rows using tableView.indexPathsForVisibleRows. Depending on if we are scrolling up or down, we compare the first or last indexPath on screen to the index path of the view that just appeared/disappeared.

//pushing up
func tableView(_ tableView: UITableView,
               didEndDisplayingHeaderView view: UIView,
               forSection section: Int) {

    //lets ensure there are visible rows.  Safety first!
    guard let pathsForVisibleRows = tableView.indexPathsForVisibleRows,
        let lastPath = pathsForVisibleRows.last else { return }

    //compare the section for the header that just disappeared to the section
    //for the bottom-most cell in the table view
    if lastPath.section >= section {
        print("the next header is stuck to the top")
    }

}

//pulling down
func tableView(_ tableView: UITableView,
               willDisplayHeaderView view: UIView,
               forSection section: Int) {

    //lets ensure there are visible rows.  Safety first!
    guard let pathsForVisibleRows = tableView.indexPathsForVisibleRows,
        let firstPath = pathsForVisibleRows.first else { return }

    //compare the section for the header that just appeared to the section
    //for the top-most cell in the table view
    if firstPath.section == section {
        print("the previous header is stuck to the top")
    }
}
like image 122
imattice Avatar answered Sep 19 '22 12:09

imattice