简体   繁体   English

didSelectItemAtIndexPath在集合视图Swift中不起作用

[英]didSelectItemAtIndexPath Doesn't Work In Collection View Swift

I have been working on a new application and it displays Gifs in a Collection View. 我一直在开发一个新应用程序,它在“收藏夹视图”中显示Gif。 I am also using a custom collection view cell class for the cells in my collection view. 我还在集合视图中的单元格使用自定义集合视图单元格类。

The method didSelectItemAtIndexPath doesn't work though ... 方法didSelectItemAtIndexPath无效,但是...

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? 我将如何更改它,以便可以使用手势识别器获取被单击项的indexPath?

as @santhu said ( https://stackoverflow.com/a/21970378/846780 ) 正如@santhu所说( https://stackoverflow.com/a/21970378/846780

didSelectItemAtIndexPath is called when none of the subView of collectionViewCell respond to that touch. 当collectionViewCell的subView都不响应该触摸时,将调用didSelectItemAtIndexPath。 As the textView respond to those touches, so it won't forward those touches to its superView, so collectionView won't get it. 由于textView响应这些触摸,因此不会将这些触摸转发到其superView,因此collectionView将无法获得它。

So, you have a UILongPressGestureRecognizer and it avoid didSelectItemAtIndexPath call. 因此,您有一个UILongPressGestureRecognizer ,它避免了didSelectItemAtIndexPath调用。

With UILongPressGestureRecognizer approach you need to handle handleLongPress delegate method. 使用UILongPressGestureRecognizer方法,您需要处理handleLongPress委托方法。 Basically you need to get gestureReconizer.locationInView and know the indexPath located at this point ( gestureReconizer.locationInView ). 基本上,您需要获取gestureReconizer.locationInView并知道此时的indexPath( 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")
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM