Search code examples
ioscore-dataswiftuiios15swiftui-form

Prefill textfields in SwiftUI is broken in iOS 15


In iOS 14 I've following code which prefills all textfields from the coredata model

struct EditSimpleSearchView: View {

   @Environment(\.managedObjectContext)
    private var viewContext
    
   @ObservedObject
   private var item: FetchedResults<SavedSearchItemEntity>.Element

   @State var includeWords: String = ""

   init(item: FetchedResults<SavedSearchItemEntity>.Element) {
      self.item = item
   }


  var body: some View {
      VStack {
                Form {
                TextField.init("Include all words", text: 
                  $includeWords).disableAutocorrection(true
                }.onAppear {
                   includeWords = item.includeWords //load from coredata in onAppear
             }
      }

As soon as I run the code, the value of includeWords appears in the textfield which is in the form.

As soon as I've updated to Xcode 13 and running on iOS 15, the value of includeWords in the textfield appears only when I input the cursor in the textfield atleast once

So far this is what I've debugged

  • No issue with colors (I mean imagine the color of the text and background were same)
  • No issue on the coredata side as the values are successfully stored in coredata.

Goal

  • As soon as user open the form, fill the text field from the coredata in iOS 15

I am currently out of ideas, any help is appreciated. I am open to suggestions incase if prefill shouldn't be configured differently.


Solution

  • Try this:

    init(item: FetchedResults<SavedSearchItemEntity>.Element) {
        self.item = item
        self._includeWords = State(initialValue: item.includeWords) // 
    }