I have an array of images loaded into a UIImageView that I am animating through one cycle. After the images have been displayed, I would like a @selector
to be
Created Swift Version from GurPreet_Singh Answer (UIImageView+AnimationCompletion) I wasn't able to create a extension for UIImageView but I believe this is simple enough to use.
class AnimatedImageView: UIImageView, CAAnimationDelegate {
var completion: ((_ completed: Bool) -> Void)?
func startAnimate(completion: ((_ completed: Bool) -> Void)?) {
self.completion = completion
if let animationImages = animationImages {
let cgImages = animationImages.map({ $0.cgImage as AnyObject })
let animation = CAKeyframeAnimation(keyPath: "contents")
animation.values = cgImages
animation.repeatCount = Float(self.animationRepeatCount)
animation.duration = self.animationDuration
animation.delegate = self
self.layer.add(animation, forKey: nil)
} else {
self.completion?(false)
}
}
func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {
completion?(flag)
}
}
let imageView = AnimatedImageView(frame: CGRect(x: 50, y: 50, width: 200, height: 135))
imageView.image = images.first
imageView.animationImages = images
imageView.animationDuration = 2
imageView.animationRepeatCount = 1
view.addSubview(imageView)
imageView.startAnimate { (completed) in
print("animation is done \(completed)")
imageView.image = images.last
}