我可以将 SwiftUI 表中的选择绑定到 Item 而不是 Item.ID 吗?

问题描述 投票:0回答:1

我有一个 SwiftUI 表,其行由 FetchedResults 填充。 为了能够触发详细信息窗格视图以显示所选表行的项目,我想将表选择映射到协调器类中的枚举。

在列表中我可以像这样直接映射它:

List(collectionEntries, id: \.self, selection: $coordinator.detailDisplay)

因为表中的选择会跟踪 ID,所以我必须像 ATM 那样进行操作。有没有更简单的表格方法?

struct CollectionTable: View {
    
    @Environment(\.managedObjectContext) private var moc
    
    let collectionEntries: FetchedResults<CollectionEntry>
    
    @State private var selected = Set<CollectionEntry.ID>()
    
    @ObservedObject var coordinator = NavigationCoordinator.shared
    
    var body: some View {
        
        Table(collectionEntries, selection: $selected) {
            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)
            }
        }
        .onChange(of: selected) { newValue in
            guard let selectedEntry = collectionEntries.first(where: { entry in
                entry.id == newValue.first!
            }) else {
                return
            }
            coordinator.detailDisplay = .entry(selectedEntry)
        }
    }
}
swiftui selection
1个回答
0
投票

使用 contextMenu 的 主要操作

.contextMenu(forSelectionType: Item.ID.self) { items in
    // ...
} primaryAction: { items in
    for item in items {
        openWindow(value: item)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.