0

I' have a code which detects last cell, but I am curious how to detect now the very first cell in tableView, because in my tableView not all cells are visible on device like iphone 7 or less that is why i have to use scroll method.

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    
    let contentOffsetMaxY: Float = Float(scrollView.contentOffset.y + scrollView.bounds.size.height)
    let contentHeight: Float = Float(scrollView.contentSize.height)
    let lastCellIsVisible = contentOffsetMaxY > contentHeight
    
    
    if lastCellIsVisible {
     //some action
    }
}
Montes
  • 1
  • 3
  • https://stackoverflow.com/questions/724892/uitableview-scroll-to-the-top – Krishnarjun Banoth May 08 '21 at 09:33
  • Does this answer your question? [UITableView - scroll to the top](https://stackoverflow.com/questions/724892/uitableview-scroll-to-the-top) – Alex Bailey May 08 '21 at 17:00
  • @AlexBailey No, i don't need scrolling action to top, I want to know how to detect all cells with my code above at least for the first cell. I managed only for a last cell to be detected. And methods like `willDisplayCell` don't work – Montes May 09 '21 at 10:53

1 Answers1

0

You can use tableView(_:willDisplay:forRowAt:) of UITableViewDelegate.

It will be called just before the cell is displayed, and will be called once for every cell.

Your code would look like this:


func viewDidLoad() {
  super.viewDidLoad()
  ...
  tableView.delegate = self
  ...
}

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  if indexPath.row == 0 {
    // First cell is going to be displayed
  }
  if indexPath.row == tableView.numberOfRows(inSection: indexPath.section) - 1 {
    // Last cell is going to be displayed
  }
}
EmilioPelaez
  • 16,368
  • 5
  • 39
  • 43