SwiftUI Animations Transitions
SwiftUI Animations: Transitions
Animate views as they insert/remove using .transition and withAnimation.
Syntax
Transition: .transition(.opacity) on the inserted/removed view.
Wrap state change in withAnimation to animate the transition.
Opacity + Scale Transition
Tap the button to insert/remove a view. The text uses a combined .opacity and .scale transition.
Example
import SwiftUI
struct TransitionDemo: View {
@State private var show = false
var body: some View {
VStack(spacing: 12) {
Button(show ? "Hide" : "Show") {
withAnimation(.easeInOut) { show.toggle() }
}
if show {
Text("Hello")
.padding(12)
.background(.blue.opacity(0.1))
.cornerRadius(8)
.transition(.opacity.combined(with: .scale))
}
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { TransitionDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the text uses a combined .opacity and .scale transition.
Asymmetric Transitions
Use .asymmetric(insertion:removal:) to customize how the view appears vs disappears.
Example
import SwiftUI
struct AsymmetricTransitionDemo: View {
@State private var show = false
var body: some View {
VStack(spacing: 12) {
Button(show ? "Hide" : "Show") {
withAnimation(.easeInOut) { show.toggle() }
}
if show {
Text("Panel")
.padding(12)
.frame(maxWidth: .infinity)
.background(.green.opacity(0.15))
.cornerRadius(8)
.transition(.asymmetric(insertion: .move(edge: .bottom).combined(with: .opacity),
removal: .move(edge: .top).combined(with: .opacity)))
}
}
.padding()
}
}
import SwiftUI
struct ContentView: View {
var body: some View { AsymmetricTransitionDemo() }
}
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup { ContentView() }
}
}
In the example above, the panel uses an asymmetric transition to move from the bottom when inserted and from the top when removed.