Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Animate cell when pressed using Swift 3

Tags:

My problem is really simple. I would like to animate a cell within a collectionView. Indeed, I would like to show a grey background behind the cell and scale down the image inside.

It would be (almost) the same effect than Pinterest:

enter image description here

I used to code that animation on buttons, but I never did that on a cell. How can link a cell to a touchUpInside or TouchDown action for example ?

like image 633
KevinB Avatar asked Aug 12 '17 15:08

KevinB


2 Answers

If you want to start animation when you touch on the cell, you can implement didHighlightItemAt. You probably want to reverse it in didUnhighlightItemAt:

override func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) {     UIView.animate(withDuration: 0.5) {         if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {                         cell.imageView.transform = .init(scaleX: 0.95, y: 0.95)             cell.contentView.backgroundColor = UIColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1)         }     } }  override func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) {     UIView.animate(withDuration: 0.5) {         if let cell = collectionView.cellForItem(at: indexPath) as? CustomCell {             cell.imageView.transform = .identity             cell.contentView.backgroundColor = .clear         }     } } 

That yields:

demo

like image 136
Rob Avatar answered Oct 30 '22 07:10

Rob


If you need implement this functionality only for the specific cell, just add this code to you cell implementation:

override var isHighlighted: Bool {   didSet {     UIView.animate(withDuration: 0.5) {       let scale: CGFloat = 0.9       self.transform = self.isHighlighted ? CGAffineTransform(scaleX: scale, y: scale) : .identity     }   } } 

It is the same answer that suggested [pgdev][1] but for isHighlighted

like image 38
Alex Shoshiashvili Avatar answered Oct 30 '22 06:10

Alex Shoshiashvili