Question

I have attached a UILongPressGestureRecognizer to a Collection View with the aim of the user hold finger on a cell in the table and being asked if they want to remove it.

The problem I have is that I can not get the indexPath like I would with a table cell (using indexPathForRowAtPoint), is there an equivalent?

If not I have thought about adding the gesture to each cell, but then how do I identify the which gesture (I can not see a "tag" for a gesture), e.g. can I send indexPath.item in the selector? Or some other method?

Was it helpful?

Solution

You got the same thing on the UICollectionView. According to the documentation:

indexPathForItemAtPoint: Returns the index path of the item at the specified point in the collection view.

  • (NSIndexPath *)indexPathForItemAtPoint:(CGPoint)point Parameters point A point in the collection view’s coordinate system. Return Value The index path of the item at the specified point or nil if no item was found at the specified point.

Discussion This method relies on the layout information provided by the associated layout object to determine which item contains the point.

Availability Available in iOS 6.0 and later. Declared In UICollectionView.h

OTHER TIPS

Please note that the CGPoint that you get sometimes is coming in the UIViewController reference system and works as long as there is no scrolling involved. When scrolling is involved you need to translate the point to the real point in the scrollable view by adding the offset of the scroll.

In this example the CGPoint is coming from a 3DTouch in the whole UIViewController that contains a UICollectionView inside

public func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController?{
    let offsetPoint = self.musicCollectionVw.contentOffset
    let realLocation = CGPoint(x: location.x + offsetPoint.x, y: location.y + offsetPoint.y)
    if let indexPath = self.musicCollectionVw.indexPathForItem(at: realLocation){
        NSLog("Section: \(indexPath.section) Row: \(indexPath.row)")
    }
    return nil
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top