How to get full transitions in SwiftUI

Animations and transitions in SwiftUI are a great way to add polish to an application and improve user experience. Modifiers, such as view transitions, are convenient and have much variety in terms of choice with what animation the view will be presented and removed from the viewport.

One caveat of the transition modifier is that sometimes it may not work as expected, depending on the type of view you have it applied to. Let’s look at an example.

struct TestView: View {
    
    @State var show = false
    
    var body: some View {
        VStack {
            Button {
                withAnimation {
                    show.toggle()
                }
            } label: {
                Text("Toggle Rectangle")
            }
            if show {
                Rectangle()
                    .transition(.slide)
                    .foregroundColor(.yellow)
                    .frame(width: 100, height: 100)
            }
        }
        .padding()
    }
}

This view will present and hide a square rectangle when the button is clicked.

Example of an incomplete transition in swiftUI.

As you may notice, the animation is not complete. The yellow square transition appearance starts not at the left edge of the screen but at about 1/4 of its width. Same with disappearance, not at the right edge but about 3/4 of the way there.

Getting complete transitions in SwiftUI:

The fix is actually pretty simple. All you have to do is apply an additional modifier to the square in order to make its max-width infinity.

// ....
Rectangle()
    .transition(.slide)
    .foregroundColor(.yellow)
    .frame(width: 100, height: 100)
    .frame(maxWidth: .infinity)

Let’s take a look at it now.

Example of a complete transition in swiftUI.

Now the transition in SwiftUI is complete. The box appears from the left edge and disappears at the right edge of the screen. And even though we set the max width modifier to infinity, the dimensions of the square are still preserved.

Notes: Make sure to apply the maxWidth modifier after you applied the desired width modifier, otherwise the animation will not work properly. The same method can also be used if the transition is vertical, in that case just use maxHeight instead.