Swift Location For Item At Index Path?

659 views Asked by At

I'm using a collection view and I'm trying to set up peek & pop to work with it. I've overridden:

func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController?

I'm trying to retrieve the index path for the item I'm clicking on by using the location variable.

Location appears to be correct but for some reason collectionView.indexPathForItem(at: location) is returning the wrong index path.

I have an idea of how to solve this issue, but I'm not sure that it is possible in Swift. Here is my thought:

Use the function indexPathForVisibleItems to retrieve all IndexPaths available. Loop through these IndexPaths and use a function that would be called something like locationForItem(at: indexPath) if it existed. I could then find the correct IndexPath based on its location.

If this is not possible, I'd be wondering if anyone else has had the same problem, where it is returning the completely wrong index path? What I believe is happening is that the spot that I'm clicking might have multiple cells, and it is grabbing the top cell in the view hierarchy, and returning the indexPath for that top cell, which might be the only one in this Z-index.

Is it possible to retrieve all index paths at a location?

Code:

override func viewDidLoad()
    if traitCollection.forceTouchCapability == .available {
        registerForPreviewing(with: self, sourceView: collectionView)
    }

override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
    guard let indexPath = collectionView.indexPathForItem(at: location)...
0

There are 0 answers