我有一个视图,它使用 @fetchrequest 包装器从 CoreData 中提取,但是它工作正常,但是当我在 .sheet 中编辑数据并返回视图时,数据不会更新,直到我离开并返回。它不应该只是自动更新吗?这是一些示例代码:
列表
import CoreData
struct Stories: View {
@State var addStory = false
@Environment(\.managedObjectContext) var moc
@FetchRequest<Story>(
entity: Story.entity(),
sortDescriptors: []
) var stories: FetchedResults<Story>
var body: some View {
ScrollView(.vertical, showsIndicators: false) {
ForEach(stories, id: \.self){ story in
GeometryReader { geometry in
StoryCard(show: story.show,
image: Image(uiImage: UIImage(data: story.image as! Data)!) ?? Image("deer3"),
title: story.title,
date:story.date,
locationTitle: story.locationTitle ?? "",
text: story.text,
timeOfDay: timeOfDayData[Int(story.tod)],
weather: weatherData[Int(story.weather)],
story: story)
.environment(\.managedObjectContext, self.moc)
.offset(y: story.show ? -geometry.frame(in: .global).minY : 0)
}.frame(height: story.show ? screen.height : 280)
.frame(maxWidth:story.show ? .infinity : screen.width-60)
.background(Color("Tan"))
.zIndex(story.show ? 2.0 : 0.5)
}
}
}
目的
struct StoryCard: View {
@State var show:Bool
@State var image:Image = Image("deer1")
@State var title = "Story title"
@State var date:Date = Date()
@State var locationTitle = "Priddis"
@State var location:CLLocationCoordinate2D = CLLocationCoordinate2D()
@State var text = "Lorem ipsum valor decor vassus sit amet."
@State var timeOfDay = timeOfDayData[0]
@State var weather = weatherData[0]
@State var edit = false
@ObservedObject var story:Story
@Environment(\.managedObjectContext) var moc
var body: some View {
....
Button(action:{
self.show.toggle()
self.moc.performAndWait {
self.story.show = self.show
try? self.moc.save()
}
self.edit.toggle()
}){
Text("Edit")
}.sheet(isPresented: self.$edit) {
ImagePickerTest(addStory: self.$edit, story:self.story).environment(\.managedObjectContext, self.moc)
}
....
}
}
编辑
struct Editor: View{
...
@State var story:Story?
@Environment(\.managedObjectContext) var moc
var body: some View {
...
Button(action:{
self.moc.performAndWait {
self.story!.title = self.storyName
self.story!.date = self.date
self.story!.locationTitle = self.locationTitle
self.story!.tod = Int16(self.tod)
self.story!.weather = Int16(self.weather)
self.story!.text = self.text
self.story!.show = false
self.story!.latitude = self.centerCoordinate.latitude
self.story!.longitude = self.centerCoordinate.longitude
self.story!.image = self.inputImage?.pngData()
try? self.moc.save()
}){
Text("Save")
}
...
}
}
任何帮助是极大的赞赏。谢谢!