Animate cell when pressed using Swift 3

后端 未结 6 2151
感情败类
感情败类 2020-12-23 10:30

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

6条回答
  •  甜味超标
    2020-12-23 11:17

    Swift 4.2, inside the UICollectionViewCell

        //MARK:- Events
        override func touchesBegan(_ touches: Set, with event: UIEvent?) {
            super.touchesBegan(touches, with: event)
            animate(isHighlighted: true)
        }
    
        override func touchesEnded(_ touches: Set, with event: UIEvent?) {
            super.touchesEnded(touches, with: event)
            animate(isHighlighted: false)
        }
    
        override func touchesCancelled(_ touches: Set, with event: UIEvent?) {
            super.touchesCancelled(touches, with: event)
            animate(isHighlighted: false)
        }
    
        //MARK:- Private functions
        private func animate(isHighlighted: Bool, completion: ((Bool) -> Void)?=nil) {
            let animationOptions: UIView.AnimationOptions = [.allowUserInteraction]
            if isHighlighted {
                UIView.animate(withDuration: 0.5,
                               delay: 0,
                               usingSpringWithDamping: 1,
                               initialSpringVelocity: 0,
                               options: animationOptions, animations: {
                                self.transform = .init(scaleX: 0.96, y: 0.96)
                }, completion: completion)
            } else {
                UIView.animate(withDuration: 0.5,
                               delay: 0,
                               usingSpringWithDamping: 1,
                               initialSpringVelocity: 0,
                               options: animationOptions, animations: {
                                self.transform = .identity
                }, completion: completion)
            }
        }
    

提交回复
热议问题