[英]Using NavigationLink in Menu (SwiftUI)
Can you use a NavigationLink
as a Menu
's item in swiftUI?您可以在 swiftUI 中使用NavigationLink
作为Menu
的项目吗?
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?如果它不能像上面尝试的那样工作,是否有实现预期结果的替代方法?
NavigationLink
should be inside NavigationView
hierarchy. NavigationLink
应该在NavigationView
层次结构中。 The Menu
is outside navigation view, so put buttons inside menu which activate navigation link placed inside navigation view, eg. Menu
在导航视图之外,因此将按钮放在菜单内,以激活放置在导航视图内的导航链接,例如。 hidden in background.隐藏在背景中。
Here is a demo of possible approach (tested with Xcode 12.1 / iOS 14.1)这是可能方法的演示(使用 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()
})
}
}
}
I can say that Asperi's answer is great solution.我可以说 Asperi 的答案是很好的解决方案。 It helped a lot.它有很大帮助。 But we need a custom view to hold a reference inside the destination property right?但是我们需要一个自定义视图来保存目标属性中的引用,对吗? not a string.不是字符串。
@State var navigateTo: AnyView?
@State var isNavigationActive = false
We can hold a reference AnyView type and then call the view like this:我们可以持有一个引用 AnyView 类型,然后像这样调用视图:
Menu {
Button {
navigateTo = AnyView(CreateItemView())
isNavigationActive = true
} label: {
Label("Create an Item", systemImage: "doc")
}
Button {
navigateTo = AnyView(CreateItemView())
isNavigationActive = true
} label: {
Label("Create a category", systemImage: "folder")
}
} label: {
Label("Add", systemImage: "plus")
}
For more detail please see this post: https://developer.apple.com/forums/thread/119583有关更多详细信息,请参阅此帖子: https ://developer.apple.com/forums/thread/119583
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.