TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Trying to figure out how view transitions work

Forums > SwiftUI

I'm using a very simple example but it doesn't work as I expect it to work...


struct ContentView: View {
    @State var change = false

    var body: some View {
        Rectangle()
            .foregroundColor(change ? .red : .green)
            .frame(maxWidth: .infinity)
            .transition(.slide)
            .onTapGesture {
                withAnimation {
                    change.toggle()
                }
            }
}

When the view is tapped, I expect to see a sliding transition. Instead, there is a fade-in/fade-out transition, both on the simulator and the device.

2      

Hi! Try this way. Run on simulator. Very often canvas doesn't handle animation in the way we expect it.

var body: some View {
        VStack {
            if change {
                Rectangle()
                    .foregroundColor(.red)
                    .transition(.move(edge: .leading))
            } else {
                Rectangle()
                    .foregroundColor(.green)
                    .transition(.move(edge: .trailing))
            }
        }
        .frame(maxWidth: .infinity)
        .onTapGesture {
            withAnimation {
                change.toggle()
            }
        }
    }

2      

Thank you, but I'm still having fade-in/fade-out with this code...

I did have a sliding transition with a similar code, replacing one Rectangle with another when the condition changes, but what I am looking for in the real app is this:

I have a grid displaying some information (a calendar). When the user swipes the view, I want the data in the grid to be changed, and when that happens, the whole grid to move, with the next month replacing the previous one.

So in my example code I am changing the colour of the Rectangle. That's a new information, sort of, and I expect SwiftUI to re-generate the view, basically replace the old Rectangle with a new one, of a different colour, and to use the transition I've specified. And it almost works, except that instead of the transition I've specified the default fade-in/fade-out transition is used.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.