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.
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.