如何检测 UICollectionView 上的屏幕位置?

How to detect screen location on UICollectionView?

应用程序需要在选择 UICollectionView 单元格时获取屏幕位置 (x,y)。

我试过touchesBegan,但没成功。我还用 UITapGestureRecognizergestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool 进行了测试,当设置为 truefalse 时,它可以使用手势或点击单元格,但不能同时使用。

有什么方法可以让这两个动作同时起作用?

谢谢。

我不确定为什么你需要同时触发这两个。无论您在一个中做什么,您都可以将该代码移动到另一个。但要回答你的问题,你可以做类似的事情。

不要使用 didSelectItemAtIndexPath。将该代码移动到 gestureRecognizer 中。如果您需要水龙头的 indexPath,请说:

let tapLocation = gesture.location(in: self.view)
let indexPath = collectionView.indexPathForItem(at: tapLocation)

如果您不喜欢,可以尝试实施

optional func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool

并返回 true 以查看是否允许调用这两种方法。