Use context menu to navigate to another view

I would like to use a context menu item to navigate into a different view.

.contextMenu {
    Button {
        // Navigate to a view
    } label: {
        Label("Add to playlist", systemImage: "music.note.list")
    }
}

There are multiple items in the context menu. I have tried to wrap the button into a NavigationLink but there is no response when selecting the context menu item.

Post not yet marked as solved Up vote post of filip.adler Down vote post of filip.adler
659 views

Replies

You can not use NavigateLink in ContextMenu, maybe you can use .sheets

something like this:

struct ContentView: View { @State var issheetshown = false var body: some View{ NavigationStack{ VStack { Text("Click To Add Text") .padding(EdgeInsets(top: 10, leading: 140, bottom: 0, trailing: 0)) .frame(maxWidth: .infinity, alignment: .leading) .contextMenu { Button { print("Type down") issheetshown = true } label: { HStack { Text("Type Down") Spacer() Image(systemName: "scribble.variable") } } } .sheet(isPresented: $issheetshown) { NotesView() }

For NotesView, it is just a average SwiftUI view, so you can just put anything that you like :). And you can alter the text and buttons however you like, Hope this will work! -Ted :D

I am able to use the contextMenu guy to navigate to another View. Do I miss something?

import SwiftUI

struct ContentView: View {
	var body: some View {
		NavigationStack {
			FirstView()
		}
	}
}

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

struct FirstView: View {
	@State var goToSecond = false

	var body: some View {
		VStack {
			Text("FirstView")
				.contextMenu {
					Button("Go to Second View") {
						goToSecond.toggle()
					}
				}
		}
		.navigationDestination(isPresented: $goToSecond) {
			SecondView()
		}
	}
}

struct SecondView: View {
	var body: some View {
		VStack {
			Text("SecondView")
		}
	}
}