Browse Questions
Answer:
SwiftUI animates changes by watching state. You trigger animations by wrapping state changes in withAnimation {} or by attaching .animation() modifiers.
Code Example:
struct AnimatedView: View {
@State private var isExpanded = false
var body: some View {
VStack {
Button("Toggle") {
withAnimation(.spring(duration: 0.4)) {
isExpanded.toggle()
}
}
if isExpanded {
Text("Expanded content")
.transition(.move(edge: .top).combined(with: .opacity))
}
}
}
}
// Animating between two views with matchedGeometryEffect
@Namespace private var animation
// Source view
Image("thumbnail")
.matchedGeometryEffect(id: "image", in: animation)
// Destination view
Image("thumbnail")
.matchedGeometryEffect(id: "image", in: animation)