SwiftUI Animations Transitions

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

Demo.swift

ContentView.swift

App.swift

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()
} }

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

Demo.swift

ContentView.swift

App.swift

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()
} }

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *