【问题标题】:ContextMenu in macOS App SwiftUI on Button TapmacOS App SwiftUI 中的 ContextMenu 按钮点击
【发布时间】:2022-01-03 21:52:57
【问题描述】:

我想点击一个按钮并在 SwiftUI 中为 macOS 应用程序显示上下文菜单。我可以看到按钮,但是当我点击按钮时没有任何反应。

let menuItems = ContextMenu {
        Button("Today") {}
        Button("Tomorrow") {}
    }

 Button {
                    // action
                } label: {
                    Label("Add Date", systemImage: "calendar")
                        .contextMenu(menuItems)
                }

有什么想法吗?

【问题讨论】:

    标签: macos swiftui


    【解决方案1】:

    在上下文菜单周围放置一个Button 意味着该按钮正在管理所有的点击事件,并且它们都没有通过contextMenu 修饰符。

    您可以移动修饰符以附加到按钮本身,您会得到一些在左键单击时执行按钮操作,但在右键单击时显示上下文菜单的内容:

      Button {
        print("Clicked")
      } label: {
        Label("Add Date", systemImage: "calendar")
      }
      .contextMenu(menuItems)
    

    【讨论】:

    • 谢谢!这项工作,但我怎样才能让它在按钮点击上工作。当我右键单击按钮时,您的代码有效。
    • 我不需要在 macOS 中左键单击上下文菜单,所以恐怕我不是 100% 知道!我在文档中能找到的最接近的是使用Menu,它会生成一个下拉式菜单。默认情况下,它会水平扩展以填充整个空间,但如果需要,您可以使用 frame 修饰符。
    • 非常感谢。我会研究更多。
    【解决方案2】:

    在我看来,您只是在寻找具有按钮样式的菜单,例如

     Menu {
          Button("Today") {}
          Button("Tomorrow") {}
     } label: {
          Label("Add Date", systemImage: "calendar")
     }
     .menuStyle(.borderedButton)
    

    【讨论】:

    • 谢谢!我更新了问题,所以显示我在找什么。
    • 是的,就是这样。
    猜你喜欢
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 2021-04-26
    • 2020-02-13
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    相关资源
    最近更新 更多