Manav
Manav

Reputation: 2520

Detect when UITableView section has scrolled out of view

I am trying to remove first section when it scrolls out of view.

I tried it using below delegate method but as i do not have footer view, it was of no help.

func tableView(_ tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int)

Also, I tried to use scroll view delegate

func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool){
  let indexPath = tableView.indexPathsForVisibleRows?.first
  if indexPath?.section == 1 {
       //remove View
  }
}

Can you tell me how to detect when first section goes out of view ?

Upvotes: 2

Views: 1585

Answers (1)

Mojtaba Hosseini
Mojtaba Hosseini

Reputation: 120062

You can use ...didEndDisplayingCell... function in delegate:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.section == 0 && indexPath.row == lastRowInFirstSection {
        // first section is out
    }
}

Note that this function is called once each cell went out from the top or bottom of the screen, so you need to check the indexPath to make sure that was the cell you need.

Also you can check if the second section is visible to detect if first section is going out from the bottom if you needed:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if indexPath.section == 0 && indexPath.row == lastRowInFirstSection {

        if tableView.indexPathsForVisibleRows?.contains (where: { $0.section == 0 }) == true {
            // It goes out from bottom. So we have to check for the first cell if needed
        } else {
            // It goes out from top. So entire section is out.
        }
    }
}

Upvotes: 6

Related Questions