Nitesh
Nitesh

Reputation: 2034

Display button when UICollectionView Cell Tapped

I'm having an Image and when user taps twice on that image then I show a button which has a tick sign as if like user has ticked that Image. I have set the button hidden at first from Storyboard.

I'm getting cell tap using this

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.subOptionsCollectionView{
        let imageNamed = "\(customizeOptionSelected[indexPath.row])"

        shirtImage.image = UIImage(named: imageNamed)

        let tap = UITapGestureRecognizer(target: self, action: #selector(doubleTapped))
        tap.numberOfTapsRequired = 2
        collectionView.addGestureRecognizer(tap)
    }
}
func doubleTapped() {
    print("Double Tap")
}

But how do I display that tick/button ?

Upvotes: 3

Views: 1776

Answers (2)

Sébastien REMY
Sébastien REMY

Reputation: 2470

Swift 4 Update :

  @IBAction func doubleTap(_ sender: UITapGestureRecognizer) {

        let buttonPosition: CGPoint = sender.location(in: self.collectionView)
        guard let indexPath = self.collectionView?.indexPathForItem(at: buttonPosition) else { return }

        print ("doubleTap on cell at: ", indexPath)

        let cell = self.collectionView.cellForItem(at: indexPath)
        // now you have the cell and have access to the button
    }

Upvotes: 1

Mina
Mina

Reputation: 2222

put your code in cellForRowAtIndexPath instead of didSelect and disable the userInteraction of collectionView then you can set the isHidden property of the button to true in doubleTapped, but you have to change the function like this(Swift3):

func doubleTapped(selectedIndex: IndexPath) {
    print("Double Tap")
}

and change the selector like this:

UITapGestureRecognizer(target: self, action: self.doubleTapped(selectedIndex: indexPath))

There is another solution:

put your code in cellForRowAtIndexPath instead of didSelect then you can set the isHidden property of the button to true in doubleTapped, but you have to change the function like this(Swift2):

func doubleTapped(sender: AnyObject) {
     let buttonPosition: CGPoint = sender.convertPoint(CGPointZero, toView: self.collectionView)
     let indexPath: NSIndexPath = self.collectionView.indexPathForRowAtPoint(buttonPosition)!
     //you have the selected cell index
     let cell = self.collectionView.cellForItemAtIndexPath(indexPath)
     //now you have the cell and have access to the button

}

and add the gesture like this:

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapped(_:)))
cell.addGestureRecognizer(tapGesture)

Upvotes: 4

Related Questions