Learn Courses My Dashboard

Two separates buttons erroneously opening the same View

In my app, I have two buttons at the top of the screen that are designed to open two different views as follows:

struct ContentView: View {

@State private var showingSheet =  false

var body: some View {
    VStack {
        ZStack {
         Image("top_toolbar")
                .resizable()
                .frame(width: 375, height: 90, alignment: .center)
                
            HStack {
                Button(action: {
                    showingSheet.toggle()
                }, label: {
                    Image(systemName: "list.bullet")
                })
                .sheet(isPresented: $showingSheet) {
                    MenuView()
                }
                Spacer()
              
                Button(action: {
                    showingSheet.toggle()
                }, label: {
                    Image(systemName: "magnifyingglass")
                })
                .sheet(isPresented: $showingSheet) {
                    SearchView()
                }
            }
        }
        MainView()
    }
}

}

The separate view files (MenuView and SearchView) both look great in the Preview canvas. When I run a live preview, tapping on the button linking to MenuView does as designed and opens MenuView in a sheet. However, tapping on the button linking to SearchView opens up MenuView. Xcode build is successful: not sure why the button for SearchView is not working properly.

Any help to correct would be greatly appreciated. Thank you in advance.

The .sheet modifier has a binding boolean property that should be unique to each sheet. So effectively you need two different @State boolean values that you change with the respective button which will then present the respective sheet.

For example, consider naming one isShowingMenuView and the other isShowingSearchView.

(edit)
What is the purpose of MainView() at the bottom of ContentView()

1 Like

Thank you, Chris. I’ll incorporate that change.

The MainView() is simply referencing a separate view that opens a list of Nav Links. I did it this way to conserve real estate space within ContentView.

UPDATE: Chris, I incorporated your recommended change, and now both buttons work flawlessly. Sincerely appreciate the help. God bless you!

1 Like