我正在构建 macOS 待办事项列表应用程序以供练习
在我看来,我有一个列表,它循环遍历 [Task] 数组(来自 swiftData 查询)
列表可选择
我想将键盘快捷键应用于所选项目的切换
task.isCompleted
我知道您可以使用
.keyboardShortcut
修饰符。
Button("complete") {
// do something
}
.keyboardShortcut("c", modifiers: [.command])
但是,我不知道如何将此快捷方式仅应用于所选项目。
列表
import SwiftUI
import Foundation
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@Query private var tasks: [TaskModel]
@State private var selections: Set<TaskModel> = []
var body: some View {
List(selection: $selections) {
ForEach(tasks, id: \.self) { task in
HStack {
Button("complete") {
task.isCompleted.toggle()
}
Text(task.name)
}
// How to perform keyboard shortcut on the selected row?
}
}
}
}
@Model
class TaskModel {
var id: UUID
var name: String
var isCompleted: Bool
init(id: UUID, name: String, isCompleted: Bool) {
self.id = id
self.name = name
self.isCompleted = isCompleted
}
}
onKeyPress
来检测关键事件。只需将以下内容添加到List
.onKeyPress(phases: .down) { press in
guard press.characters == "c", press.modifiers == .command, !selections.isEmpty else {
return .ignored
}
for selection in selections {
selection.isCompleted.toggle()
}
return .handled
}
如果您希望按住按键时重复切换,请使用
.onKeyPress(phases: [.down, .repeat])
。