I am creating a custom activity indicator view and I am having difficulty implementing the animation that I want for my indicator. The first part of the animation has the dots emerge. When the dots have emerged the following set of images are looped over to indicate that something is loading. Finally once a condition is met it will trigger the image view to animate the last set of images which make the dots disappear. In total there are 150 images.
let iv = UIImageView()
var isAnimating: Bool = false
func startAnimating() {
isAnimating = true
iv.animationImages = (0...40).map { UIImage(named: "loader_\($0)")! }
iv.animationDuration = 40 / 30
iv.animationRepeatCount = 1
iv.image = UIImage(named: "loader_40")
iv.startAnimating()
DispatchQueue.main.asyncAfter(deadline: .now() + 40 / 30) {
self.iv.image = UIImage.animatedImage(with: (41...110).map { UIImage(named: "loader_\($0)")! }, duration: 70 / 30)
Timer.scheduledTimer(withTimeInterval: 70 / 30, repeats: true) { timer in
if !self.isAnimating {
self.iv.animationImages = (111...150).map { UIImage(named: "loader_\($0)")! }
self.iv.image = UIImage(named: "loader_150")
self.iv.startAnimating()
timer.invalidate()
}
}
}
}
The first 40 images are loaded in for the starting animation. Using asyncAfter I set the animation images to an array containing 70 images related to the loading animation then a timer is called every time the loading animation completes to check if something has set the isAnimating boolean to false to then set the image view animation images to the last 40 images which are the dots disappearing.
The code works however using asyncAfter and scheduledTimer to set new animation images for the image view does not like it is the ideal solution. How am I able to create a completion handler for an image view so that when the animationImages finish playing I am able to set the animation images to a new value.