【发布时间】:2020-04-30 22:01:26
【问题描述】:
在我的核心数据学习中取得进展,我现在坚持以下几点: 我在 ContentView 中显示核心数据对象的列表。 如果用户想要编辑其中一个,他长按列表中的项目,弹出一个带有和编辑按钮的上下文表。到现在为止还挺好。 编辑按钮会召唤一个模态视图,将在该视图上进行编辑。
在编辑视图中,我首先通过存储在 UserDefaults 中的 UUID 属性获取正确的项目。
我能够显示项目的名称,但我遇到了日期问题(项目具有“eventDate”日期属性。
应用程序已构建,我在我的设备上运行它,但在我尝试编辑项目时它立即崩溃。当我将选择器要显示的值实例化为事件的日期时,我的 EditView 代码中会引发错误:
这是编辑按钮内部发生的事情:
Button(action: {
self.modalViewCaller = 1 // To tell the sheet which view to display
UserDefaults.standard.set(item.identNumber?.uuidString, forKey: kactiveEventUUID)
self.settingsModalIsPresented = true
})
{ Text("Edit entry")
Image(systemName: "globe")
}
以及我在 EditView 中获取事件的方式:
@Environment(\.managedObjectContext) var managedObjectContext
// We get the event to be edited through its UUID :
@FetchRequest(entity: Takeoffs.entity(),
sortDescriptors: [NSSortDescriptor(keyPath: \Takeoffs.eventDate, ascending: false)],
predicate: NSPredicate(format: "identNumber == %@", UUID(uuidString: UserDefaults.standard.string(forKey: kactiveEventUUID)!)! as CVarArg)) var fetchedEvent: FetchedResults<Takeoffs>
// UserDefaults.standard.object(forKey: kactiveEventUUID) as! CVarArg)
@State var selectedDate = Date()
init() { // This sets "selectedDate" to the event's value for the date picker
_selectedDate = State(initialValue: fetchedEvent.first?.eventDate ?? Date()) // The underscore is used here
}
如果有人有勇气,可以在这里找到该项目:https://github.com/Esowes/RecentExp
感谢您的帮助...
[编辑 :] 尝试下面建议的 .didAppear 解决方案,但似乎在我的身体中找不到接受 .didAppear 的视图:
var body: some View {
NavigationView {
Form {
HStack {
Text("Airport : ")
TextField(String(fetchedEvent.first?.airportName ?? ""), text: $airportNameTextfield)
.disabled(airportNameTextfield.count > 2) // To limit the textField to 3 chars (IATA code)
Button(action: {
self.airportNameTextfield = ""
}) {
Image(systemName: "clear")
}
} // END of Hstack
Picker("", selection: $typeSelectorIndex) {
ForEach(0 ..< types.count) { index in
Text(self.types[index]).tag(index)
}
}
.pickerStyle(SegmentedPickerStyle())
// Text("Selected type is: \(types[typeSelectorIndex])")
VStack {
Button(action: {
self.selectedDate = Date()
}) {
Text("Today")
}
DatePicker("",selection: $selectedDate, displayedComponents: .date)
.padding(30)
.labelsHidden()
}
} // END of Form
.navigationBarItems(
leading:
Button("Done") {
self.saveEdits()
self.presentationMode.wrappedValue.dismiss() // This dismisses the view
} // END of Button "Done"
)
.navigationBarTitle("Event edition")
} // END of Navigation View
} // END of some View
【问题讨论】:
-
我在我的示例项目中做了完全相同的事情。我通过将数据类注入内容视图和模式视图来使用另一种方法。看一看:github.com/nikhiljohn10/CoreData-MacOS