Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identify Cell after Tap Location in UICollectionView

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?

like image 688
Recycled Steel Avatar asked Jul 17 '13 10:07

Recycled Steel


2 Answers

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

like image 172
Rui Peres Avatar answered Oct 17 '22 18:10

Rui Peres


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
}
like image 3
Julio Bailon Avatar answered Oct 17 '22 17:10

Julio Bailon