0

I have a table view, I need the indexpath of the row that is passing at the very top (0,0) of the tableview, I try to use the indexPathForRow(at:) which is expecting a cgpoint, I try CGPoint.zero to get the row, but the indexPath is always nil, I read that I need to play with offset of the scrollView and that point need to be in the local coordinate but so far no luck

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    let cgPoint = CGPoint.zero
    let indexPath = tableView.indexPathForRow(at: cgPoint)
}

Thanks for any help!

goseta
  • 770
  • 1
  • 7
  • 26

2 Answers2

0

There could be only one reason why this gonna be nil because of your point not bound in tablview bounds.

Apple Documentation:

An index path representing the row and section associated with point, or nil if the point is out of the bounds of any row. point in the local coordinate system of the table view (the table view’s bounds).

Try this.

let cgPoint = CGPoint.zero

if self.tableView.frame.contains(cgPoint) {
     print("point exist so indexpath should exist")
}

Ref: Diff between bounds and frame

Muhammad Shauket
  • 2,643
  • 19
  • 40
0

You need to convert (0,0) into the table view's bounds coordinate first, like this:

// Take (0,0) from parent view, find where it locates in table view's bounds
let p = tableView.superview!.convert(.zero, to: tableView)
guard let ind = tableView.indexPathForRow(at: p) else { return }
let cell = tableView.cellForRow(at: ind)! // Do what you want

Demo gif

aunnnn
  • 1,882
  • 2
  • 17
  • 23