SwiftUI Table能否将选中项绑定至Item而非Item.ID?
更简便的SwiftUI Table选中项映射方案
核心思路是通过自定义Binding直接完成Table选中ID与协调器枚举的双向映射,省去中间的@State变量和onChange回调,逻辑更紧凑:
struct CollectionTable: View { @Environment(\.managedObjectContext) private var moc let collectionEntries: FetchedResults<CollectionEntry> @ObservedObject var coordinator = NavigationCoordinator.shared var body: some View { // 自定义双向绑定:将Table的ID选中集合与coordinator的枚举状态关联 let selectionBinding = Binding<Set<CollectionEntry.ID>>( get: { // 从协调器当前状态反向获取选中ID集合 guard case .entry(let entry) = coordinator.detailDisplay else { return [] } return [entry.id] }, set: { newIDs in // 将选中ID转换为对应条目,同步到协调器 if let id = newIDs.first, let entry = collectionEntries.first(where: { $0.id == id }) { coordinator.detailDisplay = .entry(entry) } else { // 无选中项时重置状态(根据你的枚举定义调整case) coordinator.detailDisplay = .none } } ) Table(collectionEntries, selection: selectionBinding) { TableColumn("Name") { entry in Text(entry.name ?? "n/a") } TableColumn("Type") { entry in Text(entry.type ?? "n/a") } TableColumn("Language") { entry in Text(entry.lang ?? "n/a") } TableColumn("Price") { entry in Text(entry.price_usd.description ?? "n/a") } TableColumn("Count") { entry in Text(entry.count.description) } } } }
优势
- 移除了冗余的
@State private var selected变量,减少状态维护成本 - 无需额外的
onChange监听,逻辑直接内聚在Binding中 - 支持双向同步:如果协调器的
detailDisplay从外部被修改,Table的选中状态会自动同步更新
内容的提问来源于stack exchange,提问作者Stefan
相关产品推荐
相关产品推荐

