raphael raphael - 3 months ago 25
Swift Question

tap gesture on uiimage in collectionview

In each cell of my

UICollectionView
, I have multiple object to interact with.
So instead of use
didSelect
delegate method, I really wanted to add a tap gesture on each object of the cell.

To make it simple, I removed all the other objects in the example:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! PlacesCollectionViewCell

let tap = UITapGestureRecognizer(target: self, action: "gotToSelectedPlace:")
tap.numberOfTapsRequired = 1

cell.imageView.userInteractionEnabled = true
cell.imageView.addGestureRecognizer(tap)
cell.imageView.file = places[indexPath.row].picture
cell.imageView.loadInBackground()

return cell

}


In viewDidLoad, I use a nib :

collectionView.registerNib(UINib(nibName: "PlacesCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "Cell")


UICollectionView Settings:


  • Delays Content Touches: True

  • Cancellable Content Touches: True



With this example, I can't handle the tap gesture. Nothing happen.
Did I miss something??

Thanks

Answer

try this one

 var doubletapgesture : UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "processDoubleTap:")
        doubletapgesture.numberOfTapsRequired = 1
        collectionView.addGestureRecognizer(doubletapgesture)

now handle gesture

func processDoubleTap (sender: UITapGestureRecognizer)
    {
        if sender.state == UIGestureRecognizerState.Ended
        {
            var point:CGPoint = sender.locationInView(collectionView)
            var indelPath:NSIndexPath =collectionView.indexPathForItemAtPoint(point)
            if indexPath
            {
                println("image taped")
            }
            else
            {
               //Do Some Other Stuff Here That Isnt Related;
            }
        }
    }