I am working on a list app and would like the ability to edit the list item details. I am using CoreData for the data model. Right now I am stuck on how to pass the data item from the DetailView to the EditItemView. I updated to the code to the current state I am at. I am currently getting an error in the DetailView taged to the DetailView(myItem: item) line the preview. Am I setting the @State correctly for name and passing the @Binding correctly? I think my error lies in the way I am passing the name in EditItemView(name: self.$name) to the edit view. Thoughts?
Detail View:
import CoreData
import SwiftUI
struct DetailView: View {
@Environment(\.managedObjectContext) var moc
@ObservedObject var myItem: Item
@State private var name: String
@State private var showingEditScreen = false
var body: some View {
NavigationView {
VStack {
Text(self.myItem.name ?? "Unknown Item")
Text(self.myItem.attribute ?? "Unknown attribute")
}
}
.navigationBarTitle(Text(myItem.name ?? "Unknown Item"), displayMode: .inline)
.navigationBarItems(trailing:
Button(action: {
self.showingEditScreen.toggle()
}) {
Image(systemName: "square.and.pencil")
}
)
.sheet(isPresented: $showingEditScreen) {
EditItemView(name: self.$name).environment(\.managedObjectContext, self.moc)
}
}
}
struct DetailView_Previews: PreviewProvider {
static let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
static var previews: some View {
let item = Item(context: moc)
item.name = "Test item"
item.attribute = "Test attribute"
return NavigationView {
DetailView(myItem: item)
}
}
}
Edit Item View:
import CoreData
import SwiftUI
struct EditItemView: View {
@Binding var name: String
var body: some View {
TextField("Enter Item Name", text: self.$name)
}
}
struct EditItemView_Previews: PreviewProvider {
static var previews: some View {
EditItemView(name: .constant("ItemX"))
}
}
@State private var name: Stringand.sheet(isPresented: $showingEditScreen) {EditItemView(name: self.$name).environment(\.managedObjectContext, self.moc)}in the Detail View. I really can't figure out what is the correct syntax to pass the data to the next view.