Skip to main content

How to add and remove views with a transition

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to add and remove views with a transition 관련

SwiftUI by Example

Back to Home

How to add and remove views with a transition | SwiftUI by Example

How to add and remove views with a transition

Updated for Xcode 15

You can include or exclude a view in your design just by using a regular Swift condition. For example, this adds or removes some details text when a button is tapped:

struct ContentView: View {
    @State private var showDetails = false

    var body: some View {
        VStack {
            Button("Press to show details") {
                withAnimation {
                    showDetails.toggle()
                }
            }

            if showDetails {
                Text("Details go here.")
            }
        }
    }
}

Download this as an Xcode projectopen in new window

By default, SwiftUI uses a fade animation to insert or remove views, but you can change that if you want by attaching a transition() modifier to a view.

For example, we could make several text views transition in different ways, like this:

struct ContentView: View {
    @State private var showDetails = false

    var body: some View {
        VStack {
            Button("Press to show details") {
                withAnimation {
                    showDetails.toggle()
                }
            }

            if showDetails {
                // Moves in from the bottom
                Text("Details go here.")
                    .transition(.move(edge: .bottom))

                // Moves in from leading out, out to trailing edge.
                Text("Details go here.")
                    .transition(.slide)

                // Starts small and grows to full size.
                Text("Details go here.")
                    .transition(.scale)
            }
        }
    }
}

Download this as an Xcode projectopen in new window

Similar solutions…
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
All SwiftUI property wrappers explained and compared | SwiftUI by Example

All SwiftUI property wrappers explained and compared
How to create a custom transition | SwiftUI by Example

How to create a custom transition
How to make views scroll with a custom transition | SwiftUI by Example

How to make views scroll with a custom transition
How to use Instruments to profile your SwiftUI code and identify slow layouts | SwiftUI by Example

How to use Instruments to profile your SwiftUI code and identify slow layouts

이찬희 (MarkiiimarK)
Never Stop Learning.