Alejandro
Alejandro

Reputation: 325

Get indexPath for at Point when scrolling tableView

I want to get the cell on which I pressed when I preview (UIViewControllerPreviewing), the problem is that the location that returns the method is on the view and not on the actual position of the cell when scrolling in the tableview. I'm trying this:

func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "TaskDetail", bundle: nil)

guard let detailViewController = mainStoryboard.instantiateViewController(withIdentifier: "DetailTaskViewController") as? DetailTaskViewController else { return nil }

guard let indexPath = self.listTasksUITableView.indexPathForRow(at: location) else { return nil }
                print(indexPath.row)
}

This would return an indexpath of eg 2, when I actually scroll to row 18

Upvotes: 3

Views: 519

Answers (1)

Glorfindel
Glorfindel

Reputation: 22641

As @Sulthan notes in the comments, you need to convert the coordinate to the 'local' coordinate system of listTasksUITableView with the UIView instance method convert(_:from:).

Put this line*

let convertedLocation = listTasksUITableView.convert(location, from: self)

before

guard let indexPath = ...

and use convertedLocation in that line instead of location.

I needed a similar trick for a Xamarin project where I was manually calculating coordinates (similar to location.Y - tableView.Y) and that failed when the view was scrolled. This way of converting does apply scrolling into account.

*: my Swift is too rusty to tell me whether to put guard, ! etc. there. I always rely on the compiler to tell me that.

Upvotes: 1

Related Questions