Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Animate View Transitions in SwiftUI
Written by Team Kodeco

Animating view transitions is an impressive feature in SwiftUI that makes your user interface more dynamic and visually engaging. The transition modifier in SwiftUI provides a way to animate changes in your views. It defines how a view should appear or disappear when its condition changes. The most typical scenario is when you use conditional statements in your SwiftUI views.

To illustrate this concept, let’s consider a culinary application where users can choose different types of food and get the ingredients for them.

Here is an example:

struct ContentView: View {
  @State private var showIngredients = false
  let foodItems = ["Pizza", "Burger", "Pasta"]
  @State private var selectedFood = "Pizza"

  var body: some View {
    VStack {
      Picker(selection: $selectedFood, label: Text("Please choose a food")) {
        ForEach(foodItems, id: \.self) {
          Text($0)
        }
      }
      .padding()

      Button(action: {
        withAnimation {
          showIngredients.toggle()
        }
      }) {
        Text(showIngredients ? "Hide Ingredients" : "Show Ingredients")
      }
      .padding()

      if showIngredients {
        IngredientView(food: selectedFood)
          .transition(.move(edge: .leading))
      }
      Spacer()
    }
  }
}

struct IngredientView: View {
  let food: String

  var ingredients: [String] {
    switch food {
    case "Pizza": return ["Dough", "Tomato Sauce", "Cheese", "Toppings"]
    case "Burger": return ["Bun", "Patty", "Lettuce", "Tomato", "Sauce"]
    case "Pasta": return ["Pasta", "Olive oil", "Garlic", "Tomato Sauce"]
    default: return []
    }
  }

  var body: some View {
    VStack(alignment: .leading) {
      Text("\(food) Ingredients:")
        .font(.headline)
        .padding(.top)
      ForEach(ingredients, id: \.self) { ingredient in
        Text(ingredient)
      }
    }
    .padding()
    .frame(maxWidth: .infinity, alignment: .leading)
    .background(.blue.opacity(0.2))
    .cornerRadius(10)
  }
}

Your preview should look like this after tapping Show Ingredients. Note that you must run this example in a simulator to see the expected effect.

Use the transition modifier to animation the transition between views.
Use the transition modifier to animation the transition between views.

In this example, you have a Picker view where users can select the type of food. The Show Ingredients button toggles the showIngredients state. When showIngredients is true, the IngredientView is inserted into the view hierarchy.

The transition of IngredientView is defined with a move animation. When it’s being inserted, it moves in from the leading edge (from the left), and when it’s removed, it moves back out the same way. The use of the withAnimation function ensures the transition animation is applied when the showIngredients state changes.

SwiftUI’s transition modifier is a powerful tool for adding animations when a view enters or leaves the screen. By understanding and effectively using this modifier, you can make your app’s user interface more vibrant and engaging.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.