如何将展开和折叠列表行与 Core Data 元素一起使用?
Posted
技术标签:
【中文标题】如何将展开和折叠列表行与 Core Data 元素一起使用?【英文标题】:How can I use Expand and Collapse List Rows with Core Data elements? 【发布时间】:2020-07-06 16:45:32 【问题描述】:struct AppointmentView: View
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Appoint.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Appoint.title , ascending: true)])
var appointments_title: FetchedResults<Appoint>
@State var showAddDate = false
@State var sectionState: [Int: Bool] = [:]
var body: some View
NavigationView
List
ForEach(appointments_title)
order in
HStack
Text("\(order.title)").font(.headline)
Spacer()
Text("\(order.date, formatter: ContentView.self.taskDateFormat)").font(.headline)
.contentShape(Rectangle())
.onTapGesture
self.sectionState[order] = !self.isExpanded(order)
if self.isExpanded(order)
Text("\(order.description)”)
.navigationBarTitle("My Appointment")
.navigationBarItems(trailing: Button(action: self.showAddDate = true, label: Image(systemName: "plus.circle").resizable().frame(width: 32, height: 32, alignment: .center)))
.sheet(isPresented: $showAddDate) AddDate().environment(\.managedObjectContext, self.managedObjectContext)
func isExpanded(_ order:Int) -> Bool
sectionState[order] ?? false
当我尝试运行此代码时,我会收到此错误消息; 无法将“FetchedResults ”类型的值转换为预期 参数类型'Range '
有没有办法将 'FetchedResults ' 转换为 'Range ' ?
【问题讨论】:
【参考方案1】:我想出了一些东西,它起作用了。基本上,我只是在我的 .xcdatamodeld 文件中添加另一个布尔类型的属性并将其称为“isExpanded”。每次添加新条目时,我都会将其布尔属性设置为 false。
struct AppointmentView: View
@Environment(\.managedObjectContext) var managedObjectContext
@FetchRequest(entity: Appoint.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Appoint.title , ascending: true)])
var appointments_title: FetchedResults<Appoint>
@State var showAddDate = false
//@State var sectionState: [Int: Bool] = [:]
var body: some View
NavigationView
List
ForEach(appointments_title)
order in
HStack
Text("\(order.title)").font(.headline)
Spacer()
Text("\(order.date, formatter: ContentView.self.taskDateFormat)").font(.headline)
.contentShape(Rectangle())
.onTapGesture
order.isExpanded.toggle()
if order.isExpanded
Text("\(order.description)”)
else
EmptyView()
.navigationBarTitle("My Appointment")
.navigationBarItems(trailing: Button(action: self.showAddDate = true, label: Image(systemName: "plus.circle").resizable().frame(width: 32, height: 32, alignment: .center)))
.sheet(isPresented: $showAddDate) AddDate().environment(\.managedObjectContext, self.managedObjectContext)
/*func isExpanded(_ order:Int) -> Bool
sectionState[order] ?? false
*/
【讨论】:
以上是关于如何将展开和折叠列表行与 Core Data 元素一起使用?的主要内容,如果未能解决你的问题,请参考以下文章