首页 > 解决方案 > SwiftUI 中的命令未触发

问题描述

我想接收键盘命令。
像这样尝试:

@main struct app: App {
  var body: some Scene {
    WindowGroup {
      ContentView()
    }
    .commands {
      CommandMenu("CustomCommands") {
        Button("command1",action:{print("command 1 executed")})
        .keyboardShortcut("x", modifiers: .command)
        Button("command2",action:{print("command 2 executed")})
        .keyboardShortcut("A")
      }
    }
  }
}

struct ContentView: View {
  var body: some View {
    VStack{
      Text("Command Test")
      Button("command 3",action:{print("command 3 executed")})
      .keyboardShortcut("y", modifiers: .command)
      Button("command 4",action:{print("command 4 executed")})
      .keyboardShortcut("b")
    }
    
  }
}

iPad 或 Mac 上的 Catalyst 下无法接收键盘命令。
Mac (Catalyst) 上未按预期显示菜单条目。

Xcode:版本 12.0 beta 2 (12A6163b)。
MacOS:11.0 测试版 (20A4300b)

标签: swiftmacosswiftui

解决方案


我认为,问题在于,我使用了 COMMAND-a 和 COMMAND-x 之类的“系统快捷方式”。
使用 COMMAND-1 和 Command-2 现在可以在 BigSur Beta 3 中正常工作。

使用“Command-a”作为 SwiftUI 2.0 中菜单的键盘快捷键时,我问过如何使用像 COMMAND-a 这样的“系统快捷键”。


推荐阅读