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

13
如果我将.onDeleteCommand添加到列表中,当选择一行时,编辑->删除菜单项将启用。但是,删除键不起作用。我发现该菜单项没有列出快捷方式。尝试使用CommandGroup替换它时,快捷方式变为command + delete。
如何让编辑->删除菜单项使用删除键快捷方式?或者如何在macOS上启用使用删除键删除列表中的行?

Delete Menu Item


@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")]
}
1个回答

8
在重现您的问题时,我误将delete解释为forwardDelete,因此在测试时按下了错误的按键。(从标有backspacedelete的全尺寸键盘上来看,这两个按键可能会令人困惑。)
但是,我已经让您自定义的删除命令按您的预期工作。只需确保为modifiers参数传入一个空数组:pass in an empty array for the modifiers argument
.commands {
    CommandGroup(replacing: CommandGroupPlacement.pasteboard) {
        Button("Delete", action: {
            print("Custom Delete")
        })
        .keyboardShortcut(.delete, modifiers: [])
    }
}

如果您不喜欢使用“全局命令”来操作,请在工具栏中添加删除按钮,并设置相同的键盘快捷键,调用与onDeleteCommand方法相同的delete方法。
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)
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接