fade between two UIButton images

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

    @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()
        }
    }
    
    0 讨论(0)
  • 2020-12-15 11:21

    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)
    
    0 讨论(0)
提交回复
热议问题