TextField with CoreData

You need to use ObservedObject over CoreData object and for this it is better to created separated sub-view for row, like

ForEach(items) { item in
    ItemView(item: item)
}

and ItemView

struct ItemView: View {
   @ObservedObject var item: Item

   var body: some View {
      // now binding over item title is provided by ObservedObject wrapper
      TextField("Type Response Here", text: $item.title)
   }
}

Update: handling of optional properties might differ depending on which behavior is expected. Here is possible variant:

   var body: some View {
      let text = Binding(
         get: { item.title ?? "" },
         set: { item.title = $0 }
      )
      TextField("Type Response Here", text: text)
   }

Note: entering text into field does not save CoreData object, so you need to think where to save it, possible variant is in .onCommit for TextField.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top