【问题标题】:Keyboard shortcuts in SwiftUISwiftUI 中的键盘快捷键
【发布时间】:2019-09-14 17:27:09
【问题描述】:

我正在制作一个 SwiftUI 应用程序,我想使用菜单栏添加键盘快捷键。 我已经看过苹果的视频SwiftUI on all devices,但我不知道他们是如何将menu.xib 集成到他们的应用程序中的。

#if targetEnvironment(macCatalyst)
// MacOS
#else
// iOS
#endif

也不行。 我试图在我的项目中添加一个菜单栏,但我无法编译。你知道如何添加一个吗?

【问题讨论】:

  • 请分享有问题的代码。

标签: swift macos swiftui


【解决方案1】:

在 SwiftUI 2.0(BigSur Beta3 上)中,您可以像这样非常简单地将菜单添加到 Mac 应用程序:

@main
struct AppWithMenue: App {
  var body: some Scene {
    WindowGroup {
      ContentView()      
    }
    .commands {
      MyCommands()
    }
  }
}

struct MyCommands : Commands{
  var body: some Commands {
    CommandMenu("MyCommands") {
      Section {
        Button("Command 1", action: {print ("Command 1")})
        .keyboardShortcut("1")
        Button("Command 2", action: {print ("Command 2")})
          .keyboardShortcut("2")
      }
    }
  }
}

【讨论】:

    【解决方案2】:

    但我不知道他们是如何将 menu.xib 集成到他们的应用中的。

    我认为(我没有看过视频)他们确实在 Mac 上原生实现了 SwiftUI,这意味着他们没有使用 Catalyst。

    我也遇到了完全相同的问题,我通过在 AppDelegate 中添加一个菜单项来“解决”它,然后向对该操作感兴趣的视图发送通知。这并不理想,但它确实有效。

    我使用空格键实现了一个播放动作,它部分看起来像这样:
    UIKeyCommand(input: " ", modifierFlags: [], action: #selector(togglePlay))

    有关更多信息,请参阅UIMenuBuilder 文档。

    【讨论】:

      【解决方案3】:

      您可以覆盖 AppDelegate 中的 buildMenu 函数并从那里操作菜单栏。这将在不需要 Catalyst 环境检查的情况下工作。

      override func buildMenu(with builder: UIMenuBuilder) {
          super.buildMenu(with: builder)
      
          builder.remove(menu: .services)
          builder.remove(menu: .format)
          builder.remove(menu: .toolbar)
      
          builder.insertChild(newTask(), atStartOfMenu: .file)
          builder.insertSibling(logout(), afterMenu: .about)
          builder.insertSibling(preferences(), afterMenu: .about)     
      }
      

      输入键示例:

      func newTask() -> UIMenu {
      
              let command                  = UIKeyCommand(input: "n", modifierFlags: [.command], action: #selector(onNewTask))
              command.title                = "Menu_Title_New_Task".localized()
              command.discoverabilityTitle = command.title
      
              return UIMenu(title: command.title, image: nil, identifier: "your_identifier_here", options: .displayInline, children: [command])
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-24
        • 2018-09-16
        • 2015-09-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多