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"))
  }
}
2
  • Where do you call this view from? Why do you need NavigationView if you don't navigate anywhere from here? Commented Jul 13, 2020 at 15:51
  • @Asperi it's a modal view with a title, I just removed most of the irrelevant code. Commented Jul 13, 2020 at 16:04

1 Answer 1

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)
        }
    }
}

Sign up to request clarification or add additional context in comments.

1 Comment

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 (stackoverflow.com/a/57041232/9710979) to make it work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.