如何绑定编辑核心数据数组中变量的文本字段列表?

How to bind a list of textfields that edit a variable within an a core data array?

Swift ui requires a Binding<String> 到 link 到您在文本字段中更新的值。与本机 iPhone 提醒应用程序非常相似,我希望允许内联编辑将持续存在的列表。

附加的代码仅适用,但由于它们都绑定到同一个变量,所以为每个项目提供了相同的名称。如何将其绑定到 [FruitEntity] 数组?

class CoreDataViewModel: ObservableObject {
    
    //static let instance = CoreDataViewModel()
    let container: NSPersistentContainer
    let context: NSManagedObjectContext
    @Published var savedEntities: [FruitEntity] = []
}



struct Screen: View {
    
    @StateObject var vm = CoreDataViewModel()
    
    var body: some View {
        List{
            ForEach(vm.savedEntities, id: \.self) {entity in
                VStack{
                    HStack {
                        TextField("\(entity.name ?? "Workout Name...")", text: $questionVariable)
                            .onChange(of: entity.name) { text in
                                entity.name = questionVariable
                            }
                    }
                    .onDelete(perform: vm.deleteFruit)
                    .onMove(perform: moveItem)
                }
            }
        }
    }
}

您可以将 TextField 移动到一个单独的视图,它有自己的 @State 变量用于字段,另一个变量用于实体。

创建如下所示的视图:

struct ChangeName: View {

    // Will change the entity
    let entity: FruitEntity

    // Will update the field
    @State private var questionVariable = ""

    var body: some View {

                TextField("\(entity.name ?? "Workout Name...")", text: $questionVariable)
                    .onChange(of: questionVariable) { text in
                        entity.name = text

                        // Remember to save the persistent container/ managed-object-context
                    }
    }
}

在您的主视图中调用它:

struct Screen: View {

    List{
        ForEach(vm.savedEntities, id: \.self) {entity in
            VStack{
                HStack {
                    ChangeName(entity: entity)
                }

            }
            .onDelete(perform: vm.deleteFruit)
            .onMove(perform: moveItem)
         }
     }
  }