Consolidating Animation Durations in Swift | Untold Studio Skip to main content
Untold Studio Untold Studio

Main navigation

  • About
  • Work
  • Blog
  • Handbook
  • Menu
  • Contact
  • About
  • Work
  • Blog
  • Handbook
Email Us
hello@untoldhq.com
Visit Us
P.O. Box 16391
Portland, OR 97292
Follow Us
Twitter LinkedIn
← back to blog

Consolidating Animation Durations in Swift

Editor’s Note: This post was updated for Swift 5 on May 29, 2019.

When working on a large project spanning several developers, I often find that each developer has their own personal favorite animation timing. On our latest project, I implemented a simple UIView extension that lets us standardize these durations across the app using named enum values rather than inline floats or global constants. Here's the extension:

enum AnimationDuration: TimeInterval {
    case standard = 0.25
    case slow = 0.75
    case verySlow = 1.5
    case debug = 10.0
}
 
extension UIView {
    static func animate(withDuration duration: AnimationDuration, animations: @escaping () -> Void) {
        self.animate(withDuration: duration.rawValue, animations: animations)
    }
 
    static func animate(withDuration duration: AnimationDuration,
                                    delay: TimeInterval = 0,
                                    options: UIView.AnimationOptions = [],
                                    animations: @escaping () -> Void,
                                    completion: ((Bool) -> Void)? = nil) {
        self.animate(withDuration: duration.rawValue, delay: delay, options: options, animations: animations, completion: completion)
    }
}
 
extension CAAnimation {
    var animationDuration: AnimationDuration? {
        get {
            return AnimationDuration(rawValue: self.duration)
        }
        set {
            self.duration = animationDuration?.rawValue ?? 0
        }
    }
}

And here's an example of how to use it in practice:

UIView.animate(withDuration: .slow) {
    //animate properties here
}

As always, feel free to reach out to us with questions or comments @untoldhq on Twitter.

Tags
ios
swift
swift 5
Sam Ingle
Sam Ingle
Co-founder, Engineering
You might find this post useful:
Learning to build iOS apps as a Web Developer