SwiftUI - How to create a transition animation between views without impacting child view?

1.1k Views Asked by At

In SwiftUI, I've got an overarching view setup like this:

import SwiftUI


struct ContentView: View {
    @State var index: Int = 0
    var body: some View {
        if self.index == 0{
            FirstView(index: $index)
        }
        if self.index == 1 {
            SecondView(index: $index)
                .transition(.move(edge: .bottom))
                .animation(.easeIn)
        }

    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Where I have a button in FirstView that is equivalent of:

Button(action: {
   self.index = 1
}){
   Text("Change view")
}

This works fine and all is good, but I notice that, with this method, any views conditional on an if/else statement in the child views with a transition animation (i.e. SecondView in this case), also have these animations applied.

So, for example, if SecondView was as follows:

struct SecondView: View {
    @Binding var index: Int
    @State var boolean: Bool = false
    var body: some View {
        VStack{
            if self.boolean == true {
                Text("Hello!")
            }
            Button(action: {
                self.boolean = true
            }){
                Text("change boolean")
            }
        }
    }
}

the Text("Hello") would also have the .transition(.move(edge: .bottom)) transition.

Is there any way to prevent this/a better way to create a transition animation from one view to another?

0

There are 0 best solutions below