如何在 macOS 上的 SwiftUI 应用程序的编辑菜单中启用删除键快捷方式?

joe*_*els 5 swiftui

如果我将其添加.onDeleteCommand到列表中,则在选择一行时启用“编辑”->“删除”菜单项。但是,删除键不起作用。我看到菜单项没有列出快捷方式。尝试使用 CommandGroup 替换它时,快捷方式变为 command + delete

如何让 Edit -> Delete MenuItem 使用删除键快捷方式?或者如何在 macOS 上启用使用删除键删除列表中的行?

删除菜单项


@main
struct MyApp: App {
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        // Turns it into command+delete
//        .commands {
//            CommandGroup(replacing: CommandGroupPlacement.pasteboard) {
//                Button("Delete", action: {
//                    print("Custom Delete")
//                })
//                .keyboardShortcut(.delete)
//            }
//        }
    }
}

struct ContentView: View {
    @State var data = Data()
    @State var selection = Set<Int>()
    
    var body: some View {
        List.init(data.models, id: \.id, selection: $selection) {
            Text("Name: \($0.name)")
                
        }
        .keyboardShortcut(.delete)  // This does not work
        .onDeleteCommand(perform: { // This works when clicking in the menu
            print("Delete row")
        })
    }
}

struct Model: Identifiable {
    let id: Int
    let name: String
}

struct Data {
    var models = [Model(id: 1, name: "First")]
}
Run Code Online (Sandbox Code Playgroud)

pd9*_*d95 9

在重现您的问题时,我误解deleteforwardDelete,因此在测试时按下了错误的键。(来自全尺寸键盘,其中按键带有标签backspacedelete可能会造成混淆。)

但我让您的自定义删除命令按照您的预期工作。只需确保为参数传递一个空数组modifiers

.commands {
    CommandGroup(replacing: CommandGroupPlacement.pasteboard) {
        Button("Delete", action: {
            print("Custom Delete")
        })
        .keyboardShortcut(.delete, modifiers: [])
    }
}
Run Code Online (Sandbox Code Playgroud)

如果您不喜欢使用“全局命令”来执行此操作的想法。只需使用相同的键盘快捷键将删除按钮添加到工具栏,调用delete与以下相同的方法onDeleteCommand

List.init(data.models, id: \.id, selection: $selection) {
    Text("Name: \($0.name)")
}
.keyboardShortcut(.delete, modifiers: [])
.onDeleteCommand(perform: delete)
.toolbar(content: {
    Button(action: delete){
        Image(systemName: "trash.fill")
    }
    .keyboardShortcut(.delete, modifiers: [])
    .disabled(selection.isEmpty)
})
Run Code Online (Sandbox Code Playgroud)