Last active
December 29, 2025 20:12
-
-
Save jazzychad/19d06f46edec5d545f10f2a630e561e1 to your computer and use it in GitHub Desktop.
WithAnimation SwiftUI Property Wrapper
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 | |
| @propertyWrapper | |
| struct WithAnimation<T>: DynamicProperty { | |
| @State private var _internal: T | |
| private let animation: Animation | |
| init(wrappedValue: T, _ animation: Animation? = nil) { | |
| self._internal = wrappedValue | |
| self.animation = animation ?? .default | |
| } | |
| var wrappedValue: T { | |
| get { _internal } | |
| nonmutating set { | |
| withAnimation(animation) { | |
| _internal = newValue | |
| } | |
| } | |
| } | |
| var projectedValue: Binding<T> { | |
| get { | |
| $_internal.animation(animation) | |
| } | |
| } | |
| } |
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 | |
| struct WAExample: View { | |
| @WithAnimation(.spring(duration: 1.5)) | |
| private var isLoading: Bool = false | |
| var body: some View { | |
| Button { | |
| Task { | |
| isLoading = true | |
| try? await Task.sleep(for: .milliseconds(2000)) | |
| isLoading = false | |
| } | |
| } label: { | |
| if isLoading { | |
| ProgressView() | |
| .progressViewStyle(.circular) | |
| } else { | |
| Text("Fetch") | |
| } | |
| } | |
| .buttonStyle(.borderedProminent) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment