Last active
May 1, 2022 17:32
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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