Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

swift - Using NavigationLink in Menu (SwiftUI)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

demo

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()
                })
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...