Automatic pop when @Environment in base view changes

54 Views Asked by At

In the ContentView we have a modifier set to the NavigationView which checks whether the screen is .compact or .regular. When we push the NavigationLink we go to the next screen. If we start multitasking on iPad (open 2 apps simultaneously) and change our app screen from small to big, we get pop onto the NavigationLink. Is there a way to prevent that.

struct ContentView: View {
    @State var isPresented = false
    @Environment(\.presentationMode) var presentationMode
    
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink {
                    Button("Dismiss") {
                        presentationMode.wrappedValue.dismiss()
                    }
                } label: {
                    Text("Click me")
                }
                .navigationTitle("Tab 1")
            }
        }
        .navigationViewStyle(.stack)
        .modifier(DummyModifier(isPresented: $isPresented))
    }
}

struct DummyModifier: ViewModifier {
    @Binding var isPresented: Bool
    @Environment(\.horizontalSizeClass) private var horizontalSizeClass
    
    func body(content: Content) -> some View {
        Group {
            if horizontalSizeClass == .compact {
                content
                    .sheet(isPresented: $isPresented) {
                        Text("Sheet")
                    }
            } else {
                content
                    .fullScreenCover(isPresented: $isPresented) {
                        Text("Fullscreen")
                    }
            }
        }
    }
}
0

There are 0 best solutions below