How to load TextEditor with previously saved coreData

Viewed 291

I am trying to build a simple notes style app using SwiftUI. I have managed to create an entity (ApplicationQuestion), use a TextEditor to save user input (question.answer) to an attribute of this entity and display this attribute to a view.

However, rather than save and overwrite the question.answer each time I would like to be able to edit it.

I can only find examples doing this with UIkit and the documentation doesn't explain how you can load text into the editor. I can't work out if this isn't achievable with SwiftUI and I need to use a different approach.

The answer composer currently looks like this:

struct answerComposer: View {
    
    let question: ApplicationQuestion

    @Environment(\.managedObjectContext) var moc
    @State var answerText: String = ""
    @State private var currentWordCount: Int = 0


    
    var body: some View {
        
        VStack{
            
            //Title
            Text(self.question.title?.uppercased() ?? "Unknown Title")
                  .font(.largeTitle)
            //Detail
            Text(self.question.detail ?? "Unknown detail")
                  .font(.footnote)
                  .fontWeight(.light)
            //answer
            Text(self.question.answer ?? "Unknown answer")
                .font(.body)
                .padding()

         //text editor
            
            TextEditor(text: $answerText)
                .allowsTightening(true)
                .onChange(of: answerText) { value in
                                    let words = answerText.split { $0 == " " || $0.isNewline }
                                    self.currentWordCount = words.count
                                }
                .padding()
            
            // Save Button
            Button("Save") {
           // let question = ApplicationQuestion(context: self.moc)
                question.answer = self.answerText

                try? self.moc.save()

            }
            
            
        }
        

        
    }

}
1 Answers

I assume you wanted this

struct answerComposer: View {
    
    let question: ApplicationQuestion

    @Environment(\.managedObjectContext) var moc
    @State private var currentWordCount: Int = 0

    @State private var answerText: String

    init(question: ApplicationQuestion) {
       self.question = question
       self._answerText = State(initialValue: question.answer ?? "")    // << here !!
    }

    // ... other code
}
Related