Using NavigationLink in Menu (SwiftUI)

本小妞迷上赌 提交于 2021-02-19 02:28:27

问题


Can you use a NavigationLink as a Menu's item in swiftUI?

It seems to do just nothing:

Menu {
   NavigationLink(destination: Text("test1")) {
       Text("item1")
   }
   NavigationLink(destination: Text("test2")) {
       Text("item2")
   }
} label: {
   Text("open menu")
}

In case it is meant to not work as tried above, is there an alternative way of achiving the intended reult?


回答1:


NavigationLink should be inside NavigationView hierarchy. The Menu is outside navigation view, so put buttons inside menu which activate navigation link placed inside navigation view, eg. hidden in background.

Here is a demo of possible approach (tested with Xcode 12.1 / iOS 14.1)

struct DemoNavigateFromMenu: View {
    @State private var navigateTo = ""
    @State private var isActive = false
    var body: some View {
        NavigationView {
            Menu {
                Button("item1") {
                    self.navigateTo = "test1"
                    self.isActive = true
                }
                Button("item2") {
                    self.navigateTo = "test2"
                    self.isActive = true
                }
            } label: {
                Text("open menu")
            }
            .background(
                NavigationLink(destination: Text(self.navigateTo), isActive: $isActive) {
                    EmptyView()
                })
        }
    }
}


来源:https://stackoverflow.com/questions/64845129/using-navigationlink-in-menu-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!