Skip to content

Instantly share code, notes, and snippets.

@jazzychad
Last active December 29, 2025 20:12
Show Gist options
  • Select an option

  • Save jazzychad/19d06f46edec5d545f10f2a630e561e1 to your computer and use it in GitHub Desktop.

Select an option

Save jazzychad/19d06f46edec5d545f10f2a630e561e1 to your computer and use it in GitHub Desktop.
WithAnimation SwiftUI Property Wrapper
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)
}
}
}
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