fade between two UIButton images

后端 未结 8 978
醉酒成梦
醉酒成梦 2020-12-15 10:27

i want to fade between two UIButton images for the purpose of setting favorites in a UITableView.

Currently the transition is done without effect - it just changes t

8条回答
  •  不思量自难忘°
    2020-12-15 11:13

    @SuperDuperTango's answer with tintColor added:

    extension UIButton {
        func changeImageAnimated(image: UIImage?) {
            guard let imageView = self.imageView, currentImage = imageView.image, newImage = image else {
                return
            }
            CATransaction.begin()
            CATransaction.setCompletionBlock {
                self.setImage(newImage, forState: UIControlState.Normal)
            }
            let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents")
            crossFade.duration = 0.3
            crossFade.fromValue = currentImage.CGImage
            crossFade.toValue = newImage.CGImage
            crossFade.removedOnCompletion = false
            crossFade.fillMode = kCAFillModeForwards
            imageView.layer.addAnimation(crossFade, forKey: "animateContents")
            CATransaction.commit()
    
            let crossFadeColor: CABasicAnimation = CABasicAnimation(keyPath: "contents")
            crossFadeColor.duration = 0.3
            crossFadeColor.fromValue = UIColor.blackColor()
            crossFadeColor.toValue = UIColor(red: 232.0/255.0, green: 85.0/255.0, blue: 71.0/255.0, alpha: 1.0)
            crossFadeColor.removedOnCompletion = false
            crossFadeColor.fillMode = kCAFillModeForwards
            imageView.layer.addAnimation(crossFadeColor, forKey: "animateContents")
            CATransaction.commit()
        }
    }
    

提交回复
热议问题