SwiftUI animations are declarative: animate the state change and SwiftUI interpolates the UI for you.
struct Expandable: View {
@State private var open = false
var body: some View {
VStack {
Button("Toggle") {
withAnimation(.spring()) { open.toggle() }
}
if open {
Text("Details…")
.transition(.opacity.combined(with: .slide))
}
}
}
}
- Wrap state changes in
withAnimation { }. - Or attach
.animation(_:value:)to a view. - Use
.transition()for insert/remove effects.
Summary
Animate by changing state inside withAnimation; use transitions for views that appear/disappear.