cevhers
cevhers

Reputation: 41

UICollectionView didSelectItemAt not working

I need an animation when a collection view cell is tapped. I wrote an override function for it. But UICollectionView didSelectItemAt is not working when I override touchesBegan on the custom cell.

ViewController

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    self.answersCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
    self.selectedIndex = indexPath.item
}

CustomCellClass

public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    UIView.animate(withDuration: 0.5) {
        self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
    }
}

public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
    UIView.animate(withDuration: 0.1) {
        self.transform = CGAffineTransform(scaleX: 1, y: 1)
    }
}

public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    UIView.animate(withDuration: 0.1) {
        self.transform = CGAffineTransform(scaleX: 1, y: 1)
    }
}

I want to animate the selection.

Upvotes: 0

Views: 192

Answers (1)

deniz
deniz

Reputation: 975

You wrote "I need an animation when a collection view cell is tapped...". If this is the only requirement you have, I would do this instead:

  1. Make sure your collection view allows selection like so: myCollectionView.allowsSelection = true

  2. Add a function to your CustomCell like so:

     class CustomCellClass: UICollectionViewCell {
     //configure the cell as you normally would
    
         /// animates cell after a selection
         func animateSelection() {
             //please note that this is the most basic way of animating
             //there are multiple other ways. check out the provided link below in the post
             UIView.animate(withDuration: 0.5) { 
                 self.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
             } completion: { _ in
                 UIView.animate(withDuration: 0.1) { 
                     self.transform = CGAffineTransform(scaleX: 1, y: 1)
                 }
             }
         }
     }
    
  3. call this new function during didSelectItemAt callback.

     func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
         //you don't need to do this - the cell is already selected
         //self.answersCollectionView.selectItem(at: indexPath, animated: true, scrollPosition: .centeredHorizontally)
    
         if let selectedCell = collectionView.cellForItem(at: indexPath) as? CustomCellClass {
             selectedCell.animateSelection()
         }
    
         //do other things you need to do in order to react to cell selection
         ..
     }
    

Here is the exchange that you can reference to see other animation techniques.

Upvotes: 0

Related Questions