didSelectItemAtIndexPath 在集合视图 Swift 中不起作用 [英] didSelectItemAtIndexPath Doesn't Work In Collection View Swift

查看:38
本文介绍了didSelectItemAtIndexPath 在集合视图 Swift 中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在开发一个新应用程序,它在集合视图中显示 Gif.我还为我的集合视图中的单元格使用了自定义集合视图单元格类.

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.

方法 didSelectItemAtIndexPath 虽然不起作用...

The method didSelectItemAtIndexPath doesn't work though ...

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

    println("it worked")

    // ^this did not print
}

如何更改它以便我可以使用手势识别器获取单击项目的 indexPath?

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

推荐答案

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

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

didSelectItemAtIndexPath 在没有子视图的时候调用collectionViewCell 响应该触摸.当 textView 响应那些触摸,所以它不会将这些触摸转发到它的超级视图,所以collectionView 不会得到它.

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.

所以,你有一个 UILongPressGestureRecognizer 并且它避免了 didSelectItemAtIndexPath 调用.

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

使用 UILongPressGestureRecognizer 方法,您需要处理 handleLongPress 委托方法.基本上,您需要获取 gestureReconizer.locationInView 并知道此时的 indexPath (gestureReconizer.locationInView).

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")
        }
    }

这篇关于didSelectItemAtIndexPath 在集合视图 Swift 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆