我需要定義一個通用 SwiftUI 視圖,它可以接受不同 CoreData 物體的分段提取結果,但我不確定如何定義通用視圖。
在下面的示例中,我為Patient和Doctor物體定義了兩個分段提取結果。我需要能夠將它們傳遞給通用視圖。
@SectionedFetchRequest(
sectionIdentifier: \.sectionTitle,
sortDescriptors: Patient.nameSortDescriptors(), animation: .default)
private var patients: SectionedFetchResults<String, Patient>
@SectionedFetchRequest(
sectionIdentifier: \.sectionTitle,
sortDescriptors: Doctor.nameSortDescriptors(), animation: .default)
private var doctors: SectionedFetchResults<String, Doctor>
GenericView(items: patients)
GenericView(items: doctors)
struct GenericView: View {
let items: ?????
}
uj5u.com熱心網友回復:
一種方法是不僅提供獲取的結果,還提供用于結果中每個物件的視圖。
下面的視圖對于每個物件要顯示的物件 Object 和要使用的視圖 Content 是通用的。在此示例中,我正在顯示所有物件的串列
struct GenericView<Object: NSManagedObject, Content: View>: View {
let items: SectionedFetchResults<String, Object>
let rowContent: (Object) -> Content
init(items: SectionedFetchResults<String, Object>, rowContent: @escaping (Object) -> Content) {
self.items = items
self.rowContent = rowContent
}
var body: some View {
List {
ForEach(items) { section in
Section(header: Text(section.id)) {
ForEach(section, id: \.objectID) { item in
rowContent(item)
}
}
}
}
}
}
然后您將這樣的視圖稱為示例
GenericView(items: patients, rowContent: { patient in
Text(patient.name)
})
uj5u.com熱心網友回復:
如果例如DoctorandPatient符合協議Human,那么它可能如下
protocol Human {
var name: String { get set }
// other code here
}
class Doctor: NSManagedObject, Human {
var name: String = ""
// other code here
}
struct GenericView<T: NSManagedObject & Human>: View {
let items: SectionedFetchResults<String, T>
var body: some View {
// other code here
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/426108.html
下一篇:如何為RecyclerView配接器創建一個包裝器,該包裝器將接受任何實作RecyclerView.Adapter<RecyclerView.ViewHolder>的配接器
