Jeshua Lacock Jeshua Lacock - 6 months ago 120
Swift Question

Better alternative to timer based animation for custom activity indicator?

I have a class that displays a custom indeterminate progress indicator. Each timer update it simply increments the rotation of a UIImageView using CGAffineTransformRotate.

This all works, however, I noticed that when it is running, the background process that it is waiting for runs 50% slower - which is a huge penalty. For instance; instead of taking say 20 seconds to complete the processing it takes 30 seconds. Can someone recommend a solution with less performance penalty?

func show() {
timer?.invalidate()
timer = NSTimer.scheduledTimerWithTimeInterval(0.03, target: self, selector: #selector(self.updateTimer(_:)), userInfo: nil, repeats: true)
}

func updateTimer(sender: NSTimer) {
iconView.transform = CGAffineTransformRotate(iconView.transform, 0.15)
}

Answer

Use Core Animation to animate the rotation. The window server will do all the work outside of your app's process.

let animation = CABasicAnimation(keyPath: "transform.rotation")
animation.fromValue = 0
animation.toValue = 2 * M_PI
animation.repeatCount = .infinity
animation.duration = 1.25
iconView.layer.addAnimation(animation, forKey: animation.keyPath)