考虑以下视图代码:
Text("Something")
.contextMenu {
// Some menu options
}这可以很好地工作。我想做的是:通过视图修饰符间接地表示contextMenu。如下所示:
Text("Something")
.modifier(myContextMenu) {
// Some menu options
}为什么:我需要在修饰符中做一些逻辑来有条件地显示或不显示菜单。我找不出正确的视图修饰符签名。
还有另一个可用的contextMenu修饰符,它声称我可以有条件地显示它的上下文菜单。在尝试时,这对我没有帮助,因为一旦我向iOS上的NavigationLink添加contextMenu修饰符,它上的点击手势就会停止工作。下面的回复中有讨论。
如何使用视图修饰符显示上下文菜单?
发布于 2020-02-04 17:07:25
这是我想出来的。不能完全满意,它可以更紧凑,但它的工作如预期。
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")
}
}
}发布于 2020-01-26 08:56:05
像这样的东西?
Text("Options")
.contextMenu {
if (1 == 0) { // some if statements here
Button(action: {
//
}) {
Text("Choose Country")
Image(systemName: "globe")
}
}
}发布于 2020-01-26 13:30:24
以下是可选上下文菜单用法的演示(使用Xcode11.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)
}
}
}https://stackoverflow.com/questions/59913432
复制相似问题