Ian Warburton
Ian Warburton

Reputation: 15706

How can I check a if screen is on the navigation stack?

Given this...

NavigationLink(destination: Text("Hello")) {
   Text("Press")
}

And this...

.sheet(isPresented: $viewModel.showComplete) {
   Text("Hello")
}

How can I make the sheet only open if a view opened by the NavigationLink doesn't currently exist?

Upvotes: 2

Views: 1491

Answers (1)

pawello2222
pawello2222

Reputation: 54601

You may access the isActive parameter of NavigationLink and use it in a custom binding to determine whether to open the sheet.

Here is a simple demo:

struct ContentView: View {
    @State var showSheet = false
    @State var linkActive = false
    
    var binding: Binding<Bool> {
        .init(get: {
            showSheet && !linkActive
        }, set: {
            showSheet = $0
        })
    }

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(
                    destination: DetailView(showSheet: $showSheet),
                    isActive: $linkActive
                ) {
                    Text("Go to...")
                }
                Button("Open sheet") {
                    self.showSheet.toggle()
                }
            }
        }
        .sheet(isPresented: binding) {
            Text("Hello")
        }
    }
}

struct DetailView: View {
    @Binding var showSheet: Bool

    var body: some View {
        Button("Open sheet") {
            self.showSheet.toggle()
        }
    }
}

Upvotes: 1

Related Questions