2

I'm trying to bind a text field value to a core data object and I am getting a Cannot find '$draft' in scope error. I've tried moving the draft declaration out of body, adding @State let and @State var to the declaration as well, only to get another error thrown at me saying I can't use property wrappers on local properties.

Is there a correct way to do this?

struct AddItemView: View {
  @Environment(\.managedObjectContext) var moc
  @Environment (\.presentationMode) var presentationMode
              
  var body: some View {
    @State let draft = Item(context: moc)

    NavigationView {
      HStack {
        TextField("Title", text: $draft.title)
      }
    }
    .navigationTitle(Text("Add an Item"))
  }
}
Pranav Kasetti
  • 8,770
  • 2
  • 50
  • 71
ccamaisa
  • 107
  • 2
  • 8

1 Answers1

1

Ok, let's separate it a bit... and all becomes working

struct AddItemView: View {
    @Environment(\.managedObjectContext) var moc
    @Environment (\.presentationMode) var presentationMode
                
    var body: some View {
        NavigationView {
            NewItemEditor(draft: Item(context: moc))
        }
        .navigationTitle(Text("Add an Item"))
    }
}

struct NewItemEditor: View {
    @ObservedObject var draft: Item
                
    var body: some View {
        HStack {
            TextField("Title", text: $draft.title)
        }
    }
}

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • wow... thanks! just one thing to note: I get an error because draft.title is an optional and the TextField can't take those. I used the extension here (https://stackoverflow.com/a/57041232/9710979) to make it work – ccamaisa Jul 13 '20 at 16:35