didSelectItemAtIndexPath Doesn't Work In Collection View Swift

时间:2015-07-28 16:04:52

标签: ios objective-c swift uicollectionview uicollectionviewcell

I have been working on a new application and it displays Gifs in a Collection View. I am also using a custom collection view cell class for the cells in my collection view.

The method didSelectItemAtIndexPath doesn't work though ...

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    println("it worked")

    // ^this did not print
}

How would I change it so I can get the indexPath of the clicked item using a gesture recognizer?

1 个答案:

答案 0 :(得分:6)

as @santhu said (https://stackoverflow.com/a/21970378/846780)

didSelectItemAtIndexPath is called when none of the subView of collectionViewCell respond to that touch. As the textView respond to those touches, so it won't forward those touches to its superView, so collectionView won't get it.

So, you have a UILongPressGestureRecognizer and it avoid didSelectItemAtIndexPath call.

With UILongPressGestureRecognizer approach you need to handle handleLongPress delegate method. Basically you need to get gestureReconizer.locationInView and know the indexPath located at this point (gestureReconizer.locationInView).

    func handleLongPress(gestureReconizer: UILongPressGestureRecognizer) {
        if gestureReconizer.state != UIGestureRecognizerState.Ended {
            return
        }

        let p = gestureReconizer.locationInView(self.collectionView)
        let indexPath = self.collectionView.indexPathForItemAtPoint(p)

        if let index = indexPath {
            var cell = self.collectionView.cellForItemAtIndexPath(index)
            // do stuff with your cell, for example print the indexPath
             println(index.row)
        } else {
            println("Could not find index path")
        }
    }