Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Last active May 1, 2022 17:32
Show Gist options
  • Save andresr-dev/4ffc088226aa034766068d09263b8f8b to your computer and use it in GitHub Desktop.
Save andresr-dev/4ffc088226aa034766068d09263b8f8b to your computer and use it in GitHub Desktop.
This helps you to run an optional animation depending on a condition without needing to put your conditional logic inside your withAnimation closure. In this example we support Reduce Motion Accessibility
import SwiftUI
// MARK: GLOBAL FUNCTION
func withOptionalAnimation<Result>(_ animation: Animation? = .default, _ body: () throws -> Result) rethrows -> Result {
// Evaluate the parameter you want to check: ReduceMotion in this case
if UIAccessibility.isReduceMotionEnabled {
// The body gets executed without animation
return try body()
} else {
// The body gets executed with animation
return try withAnimation(animation, body)
}
}
// MARK: USE CASE
struct MyView: View {
@State private var scale = 1.0
var body: some View {
Text("Hello")
.scaleEffect(scale)
.onTapGesture {
withOptionalAnimation {
scale *= 1.5
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment