Animating SwiftUI Views: How to Add Transitions and Effects to Your User Interface

SwiftUI provides a great way to show and animate a new view on top of your current view. You have access to preset transitions like opacity, scale and slide. You have even more control with move, scale and offset transitions.

Animate your screens using the transition modifier and preset animations

View Transition  

  • To show a new view with transition, you can use the if statement with a show boolean state. 
  • On that new view, apply a transition modifier. 
  • The zIndex modifier ensures that when dismissing, the new view stays on top.

struct ContentView: View {
    @State var show = false
    
    var body: some View {
        
        ZStack {
            if !show {
                Text("View transition")
            } else {
                VStack { Text("New View") }
                    .transition(.move(edge: .bottom))
                    .zIndex(1)
            }
        }
        .onTapGesture {
            show.toggle()
        }
            
    }
}

Note: the Preview won't show an accurate representation of the transition. It is best to experience in iOS Simulator or on device.

..

Opacity Transition  

The opacity transition makes the view fade in when inserted and fade out when removed.

.transition(.opacity)

..

Scale Transition  

The scale transition enlarges a view when inserted and shrinks when removed.

.transition(.scale)

You can also customize the scale multiplier and position.

.transition(.scale(scale: 0.1, anchor: .bottom))

..

Slide Transition  

The slide transition moves in a view from the left and dismisses to the right.

.transition(.slide)

..

Move Transition  

When you use move, the view slides in and dismisses in the same direction specified.

.transition(.move(edge: .bottom))

..

Offset Transition  

The offset transition is similar to the move transition, except you have more control on the x and y position.

.transition(.offset(x: 300, y: 300))

..

Final Output:

struct ContentView: View {
    @State var show = false

    var body: some View {
        ZStack {
            if !show {
                Text("View Transitions and Animations")
                    .padding()
                    .background(Capsule().stroke())
            } else {
                RoundedRectangle(cornerRadius: 30)
                    .fill(Color.pink)
                    .padding()
                    .transition(.move(edge: .top))
                    .zIndex(1)
            }
        }
        .onTapGesture {
            withAnimation(.spring()) {
                show.toggle()
            }
        }
    }
}

..

Comments