I have a data entry view that lets the user add an image and see the preview after doing so.
The ImagePickerView
I have returns a UIImage
which I save to Core Data as type Data
through the .pngData
converter. However, after selecting the image, the view does not update to show it even though I am using @ObservedObject
and objectWillChange
I can't use @State
because the draft object is an NSManagedObject
import SwiftUI
import CoreData
struct AddItemView: View {
@Environment(\.managedObjectContext) var moc
@Environment (\.presentationMode) var presentationMode
@State var showImagePicker: Bool = false
@ObservedObject var draft: Item //Core Data entity
var body: some View {
NavigationView {
VStack {
if (draft.image != nil) {
Image(uiImage: UIImage(data: draft.image!)!)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: UIScreen.main.bounds.width - 32, height: UIScreen.main.bounds.height / 4)
.clipShape(RoundedRectangle(cornerRadius: 20))
} else {
Button(action: {
self.showImagePicker = true
}, label: {
RoundedRectangle(cornerRadius: 20)
})
.padding([.all], 20)
}
}
.sheet(isPresented: $showImagePicker) {
ImagePickerView(sourceType: .photoLibrary) { image in
draft.objectWillChange.send()
draft.image = image.pngData()
}
}
}
}
}
Try using objectWillChange.send()
after you make your changes:
.sheet(isPresented: $showImagePicker) {
ImagePickerView(sourceType: .photoLibrary) { image in
draft.image = image.pngData() // #1
draft.objectWillChange.send() // #2
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.