Search code examples
iosuicollectionviewtouchgesturetap

How to detect screen location on UICollectionView?


The App needs to get the screen location(x,y) when a UICollectionView cell is selected.

I had tried touchesBegan, but it fail to work. And I had also tested with UITapGestureRecognizer and gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool, when set it true or false, it works with either gesture or tapping on a cell, not both.

Any way to get the two actions work at the same time?

Thanks.


Solution

  • I'm not sure why you need both of those to fire. Whatever you're doing in one you could just move that code to the other. But to answer you question you can do something like.

    Don't use didSelectItemAtIndexPath. Move that code into the gestureRecognizer. If you need the indexPath for the tap say something like:

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

    If you don't like that you can try implementing

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

    And returning true to see if that will allow both methods to be called.