fade between two UIButton images

后端 未结 8 985
醉酒成梦
醉酒成梦 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:11

    This is a slight improvement to @Ponja's answer that generally works well. Unfortunately, the newImage doesn't "stick", so if you wanted to toggle between two images, the first fade would work smoothly, but going back to the original image would "snap" back with no fade. Fixed it by using a CATransaction:

    import UIKit
    
    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()
        }
    }
    

提交回复
热议问题