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
@SuperDuperTango's answer in Swift 4.2:
extension UIButton {
func changeImageAnimated(image: UIImage?) {
guard let imageView = self.imageView, let currentImage = imageView.image, let newImage = image else { return }
CATransaction.begin()
CATransaction.setCompletionBlock {
self.setImage(newImage, for: .normal)
}
let crossFade: CABasicAnimation = CABasicAnimation(keyPath: "contents")
crossFade.duration = 0.3
crossFade.fromValue = currentImage.cgImage
crossFade.toValue = newImage.cgImage
crossFade.isRemovedOnCompletion = false
crossFade.fillMode = CAMediaTimingFillMode.forwards
imageView.layer.add(crossFade, forKey: "animateContents")
CATransaction.commit()
}
}
jkanter answer in Swift:
let crossFade = CABasicAnimation.init(keyPath: "contents")
crossFade.duration = 0.7
crossFade.fromValue = oldImage.cgImage
crossFade.toValue = newImage.cgImage
crossFade.isRemovedOnCompletion = false
crossFade.fillMode = kCAFillModeForwards
button.imageView?.layer.add(crossFade, forKey: "animateContents")
//Make sure to add Image normally after so when the animation
//is done it is set to the new Image
button.setImage(newImage, for: .normal)