SwiftUI - Know what the previous view was

Viewed 73

I would like to know if there is a simple function in SwiftUI to set conditions, i.e. to know what view we were in, in the .onAppear function.

For example: there are two views "View1" and "View2" which lead to a view "View3". I would like the "turn" variable of View3 to be true if the previous view was View1 and false if the previous view was View2.

My example code :

struct View3: View {
    @State var turn: Bool
    var body: some View {
        Text("aaa")
        .onAppear {
            if /*previousView*/ == View1 {
                self.turn = true
            } else if /*previousView*/ == View2 {
                self.turn = false
            }
        }
        
    }
}

Do you know the easiest way to solve this problem? Thank you for your help

1 Answers

Simplest way:

struct View1: View {
    var body: some View {
        // ... other code

        View3(turn: true)

        // ... other code
    }
}

struct View2: View {
    var body: some View {
        // ... other code

        View3(turn: false)

        // ... other code
    }
}

struct View3: View {
    let turn: Bool
    var body: some View {
        Text("aaa")
    }
}
Related