[英]How do I present a SwiftUI context menu conditionally?
Consider the following view code:考虑以下视图代码:
Text("Something")
.contextMenu {
// Some menu options
}
This works fine.这工作正常。 What I would like to do: present the contextMenu through a view modifier indirection.
我想做的:通过视图修饰符间接呈现 contextMenu。 Something like this:
像这样的东西:
Text("Something")
.modifier(myContextMenu) {
// Some menu options
}
Why: I need to do some logic inside the modifier to conditionally present or not present the menu.为什么:我需要在修饰符内部做一些逻辑来有条件地显示或不显示菜单。 I can't work out the correct view modifier signature for it.
我无法为它计算出正确的视图修饰符签名。
There is another contextMenu modifier available which claims that I can conditionally present the context menu for it.还有另一个 contextMenu 修饰符可用,它声称我可以有条件地为其呈现上下文菜单。 Upon trying this out, this does not help me, because as soon as I add contextMenu modifier to a NavigationLink on iOS, the tap gesture on it stops working.
尝试此操作后,这对我没有帮助,因为一旦我将 contextMenu 修饰符添加到 iOS 上的 NavigationLink,其上的点击手势就会停止工作。 There is discussion in a response below.
在下面的回复中有讨论。
How do I present a context menu using a view modifier?如何使用视图修饰符呈现上下文菜单?
Something like this?像这样的东西?
Text("Options")
.contextMenu {
if (1 == 0) { // some if statements here
Button(action: {
//
}) {
Text("Choose Country")
Image(systemName: "globe")
}
}
}
Here is a demo for optional context menu usage (tested with Xcode 11.2 / iOS 13.2)这是可选上下文菜单用法的演示(使用 Xcode 11.2 / iOS 13.2 测试)
struct TestConditionalContextMenu: View {
@State private var hasContextMenu = false
var body: some View {
VStack {
Button(hasContextMenu ? "Disable Menu" : "Enable Menu")
{ self.hasContextMenu.toggle() }
Divider()
Text("Hello, World!")
.background(Color.yellow)
.contextMenu(self.hasContextMenu ?
ContextMenu {
Button("Do something1") {}
Button("Do something2") {}
} : nil)
}
}
}
Here's what I came up with.这就是我想出的。 Not entirely satisfied, it could be more compact, but it works as expected.
不完全满意,它可能更紧凑,但它可以按预期工作。
struct ListView: View {
var body: some View {
NavigationView {
List {
NavigationLink(destination: ItemView(item: "Something")) {
Text("Something").modifier(withiOSContextMenu())
}.modifier(withOSXContextMenu())
}
}
}
}
struct withOSXContextMenu: ViewModifier {
func body(content: Content) -> some View {
#if os(OSX)
return content.contextMenu(ContextMenu {
ContextMenuContent()
})
#else
return content
#endif
}
}
struct withiOSContextMenu: ViewModifier {
func body(content: Content) -> some View {
#if os(iOS)
return content.contextMenu(ContextMenu {
ContextMenuContent()
})
#else
return content
#endif
}
}
func ContextMenuContent() -> some View {
Group {
Button("Click me") {
print("Button clicked")
}
Button("Another button") {
print("Another button clicked")
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.