Ken*_*and 5 core-data nsfetchedresultscontroller swiftui
回到objective-c,我可以使用这样的东西从Core Data中获取一个分段的对象列表:
self.fetchedResultsController = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:@"ispurchased"
cacheName:nil];
Run Code Online (Sandbox Code Playgroud)
然后 NSFetchedResultsController 会自动为我提供部分和行中的数据。
我是第一次尝试 SwiftUI,我正在尝试弄清楚如何实现这样的分段列表。我发现很多示例使用了一些以分段方式预先构造的固定数组数据,但我不知道如何进行分段 FetchRequest,也不知道如何将其与 List 集成。
struct EasyModeList: View {
@FetchRequest(
sortDescriptors: [
NSSortDescriptor(keyPath: \EasyMode.ispurchased, ascending: true),
NSSortDescriptor(keyPath: \EasyMode.ispurchasable, ascending: false),
NSSortDescriptor(keyPath: \EasyMode.name, ascending: true),
],
animation: .default)
var easymodes: FetchedResults<EasyMode>
@Environment(\.managedObjectContext)
var viewContext
var body: some View {
List {
ForEach(self.easymodes, id: \.self) { easymode in
NavigationLink(
destination: DetailView(easymode: easymode)
) {
VStack {
Text("\(easymode.name!)")
}
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
SwiftUI 是否可以轻松支持这些类型的分段列表?我应该将大脑转移到不同的范式吗?
我也在寻找适当的解决方案。现在我将分享我所尝试过的。我的部分是按字符串标题排列的,但我会根据您的数据进行调整。
@FetchRequest(...) var managedEasyModes: FetchedResults<EasyMode>
private var easyModes: [String: [EasyMode]] {
Dictionary(grouping: managedEasyModes) { easymode in
easymode.ispurchased ? "Purchased" : "Not Purchased"
}
}
private var sections: [String] {
easyModes.keys.sorted(by: >)
}
var body: some View {
ForEach(sections, id: \.self) { section in
Section(header: Text(section)) {
ForEach(easyModes[section]!) { easyMode in
NavigationLink(destination: EasyModeView(easyMode: easyMode)) {
EasyModeRowView(easyMode: easyMode)
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
522 次 |
| 最近记录: |