Explicit Animations
1. withAnimation
Button("Toggle") {
withAnimation {
isExpanded.toggle()
}
}2. Custom Animation
withAnimation(.spring(response: 0.5, dampingFraction: 0.6)) {
isExpanded.toggle()
}
withAnimation(.easeInOut(duration: 0.3)) {
offset = 100
}3. Multiple Changes
Button("Animate") {
withAnimation(.spring()) {
scale = 1.5
rotation = 45
opacity = 0.5
}
}4. Completion Handler (iOS 17+)
withAnimation(.easeInOut(duration: 0.5)) {
isVisible = false
} completion: {
// Animation completed
removeItem()
}5. Ví dụ Menu
struct AnimatedMenu: View {
@State private var isOpen = false
var body: some View {
VStack {
Spacer()
if isOpen {
VStack(spacing: 16) {
MenuButton(icon: "photo", delay: 0.1)
MenuButton(icon: "doc", delay: 0.2)
MenuButton(icon: "gear", delay: 0.3)
}
}
Button {
withAnimation(.spring(response: 0.4, dampingFraction: 0.6)) {
isOpen.toggle()
}
} label: {
Image(systemName: "plus")
.rotationEffect(.degrees(isOpen ? 45 : 0))
.font(.title)
.padding()
.background(.blue)
.foregroundColor(.white)
.clipShape(Circle())
}
}
}
}📝 withAnimation vs .animation
| withAnimation | .animation |
|---|---|
| Explicit control | Automatic |
| Wraps state changes | Modifier on view |
| Multiple properties | Single view tree |
Last updated on