Skip to Content

Transitions trong SwiftUI

1. Built-in Transitions

if isVisible { Text("Hello") .transition(.opacity) } if isVisible { Text("Slide in") .transition(.slide) } if isVisible { Text("Scale") .transition(.scale) } if isVisible { Text("Move") .transition(.move(edge: .bottom)) }

2. Combined Transitions

.transition(.opacity.combined(with: .scale)) .transition(.move(edge: .bottom).combined(with: .opacity))

3. Asymmetric Transitions

.transition(.asymmetric( insertion: .move(edge: .leading), removal: .move(edge: .trailing) ))

4. Ví dụ Toast

struct ToastView: View { @Binding var isShowing: Bool let message: String var body: some View { if isShowing { Text(message) .padding() .background(.black.opacity(0.8)) .foregroundColor(.white) .cornerRadius(10) .transition(.move(edge: .top).combined(with: .opacity)) .onAppear { DispatchQueue.main.asyncAfter(deadline: .now() + 2) { withAnimation { isShowing = false } } } } } }

📝 Tóm tắt

TransitionEffect
.opacityFade in/out
.scaleGrow/shrink
.slideSlide from edge
.move(edge:)Move from specific edge
Last updated on