@SuperDuperTango 对 tintColor 的回答添加了:
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()
}
}