Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 698
Nitesh Avatar asked Apr 29 '26 04:04

Nitesh


2 Answers

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)
like image 97
Mina Avatar answered Apr 30 '26 16:04

Mina


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
    }
like image 45
Sébastien REMY Avatar answered Apr 30 '26 16:04

Sébastien REMY



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!