Jeshua Lacock Jeshua Lacock - 2 years ago 216
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 = 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 Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download