Home > Software engineering >  How to bind a textfield text to a coredata attribute
How to bind a textfield text to a coredata attribute

Time:12-19

I have a coredata entity called 'fruit'. I have an attribute for fruit called 'fruitName' of type String. I want to display this attribute in a TextField() rather than just a Text() so that users can more easily edit this attribute. I'm having trouble binding the the text argument in the TextField to the fruit.fruitName.

Here's the code:

import CoreData

struct FruitRowView: View {
    
    //instance of core data model
    @ObservedObject var vm: CoreDataViewModel
    
    var fruit: FruitEntity
    
    var body: some View {
        TextField("Enter fruit name", text: $fruit.name)
    }
}

the error that I'm getting when I try to build is: 'Cannot find '$fruit' in scope' which I take to mean that I can't bind a variable this way. I'm sure there's an easy way to work around this so that I can display this attribute in the TextField but I haven't been able to figure it out.

CodePudding user response:

To "...bind a textfield text to a coredata attribute" you could try this approach, where you declare @ObservedObject var fruit: FruitEntity. Since CoreData uses optionals, you also need to test for non nil values as shown in the code.

struct FruitRowView: View {
    @ObservedObject var fruit: FruitEntity
    
    var body: some View {
        VStack {
            if fruit.name != nil {
                TextField("Enter fruit name", text: Binding($fruit.name)!)
            }
        }
        .onAppear {
            if fruit.name == nil {
                fruit.name = ""
            }
        }
    }
}
  • Related