macOS 删除所选 List row

双击 List row 删除

1
2
3
4
5
6
7
8
9
10
11
12
List(selection: $selection) {
ForEach(items, id: \.self) { item in
Text(item)
.contextMenu {
Button(action: {
// delete item in items array
}){
Text("Delete")
}
}
}
}

SwiftUI on macOS: How to enable UI for onDelete (deletion from List)

通过按钮删除

macOS SwiftUI: how to trigger deleting an item?

通过 onDeleteCommand 删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct ContentView: View {
@State private var data = ["Item1", "Item2", "Item3"]
@State private var selection: Set<String> = []
@State private var lastForcedId = UUID()

var body: some View {
NavigationView {
List(data, id: \.self, selection: $selection) { item in
Text(item)
}
.onDeleteCommand {
data.removeAll(where: selection.contains) // Removes selected items
selection.removeAll()
lastForcedId = UUID()
}
.id(lastForcedId) // Update View

Text("Second Panel")
}
}
}

onDeleteCommand menu item is always enabled


macOS 删除所选 List row
https://wonderhoi.com/2024/12/19/macOS-删除所选-List-row/
作者
wonderhoi
发布于
2024年12月19日
许可协议