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.