Skip to content

Instantly share code, notes, and snippets.

@PimCoumans
Last active April 22, 2022 09:51
Show Gist options
  • Save PimCoumans/67683390f7769dcfe284a45f77ace5cc to your computer and use it in GitHub Desktop.
Save PimCoumans/67683390f7769dcfe284a45f77ace5cc to your computer and use it in GitHub Desktop.
Adds CAMediaTimingFunction to UIView animation using a convenient CATransaction wrapper method
extension CATransaction {
/// Executes the provided `actions` closure wrapped in `CATransaction`.
/// Optionally adds all the specific properties to commit the transaction with
/// - Parameters:
/// - duration: Duration of transaction
/// - timingFunction: Specific timing function to use with transaction
/// - disableActions: Wether actual animation should happen during transaction
/// - actions: What to do while transaction is commited
/// - completion: Closure to be executed when transaction is completes
///
/// Example to disable animations for a specific change
/// ```
/// CATransaction.perform(disableActions: true) {
/// view.frame = newFrame
/// }
class func perform(
withDuration duration: TimeInterval? = nil,
timingFunction: CAMediaTimingFunction? = nil,
disableActions: Bool? = nil,
actions: () -> Void,
completion: (() -> Void)? = nil
) {
CATransaction.begin()
duration.map { CATransaction.setAnimationDuration($0) }
timingFunction.map { CATransaction.setAnimationTimingFunction($0) }
disableActions.map { CATransaction.setDisableActions($0) }
completion.map { CATransaction.setCompletionBlock($0) }
actions()
CATransaction.commit()
}
}
extension UIView {
/// Perform a `UIView` animation with a `CAMediaTimingFunction`
/// - Parameters:
/// - duration: Duration of animation
/// - delay: Delay after which to start the animation
/// - options: Animation options (curve options would probably be ignored)
/// - timingFunction: `CAMediaTimingFunction` to be used for animation interpolation
/// - animations: Closure in which animatable properties should be changed
/// - completion: Optional closure to be exectued when animation finishes
class func animate(
withDuration duration: TimeInterval,
delay: TimeInterval = 0,
options: AnimationOptions = [],
timingFunction: CAMediaTimingFunction,
animations: @escaping () -> Void,
completion: ((_ finished: Bool) -> Void)? = nil
) {
CATransaction.perform(
withDuration: duration,
timingFunction: timingFunction) {
UIView.animate(withDuration: duration, delay: delay, options: options, animations: animations)
} completion: {
completion?(true)
}
}
}
@PimCoumans
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment