将核心数据对象绑定到输入 SwiftUI

2023-12-28

我正在使用 SwiftUI 创建一个小锻炼应用程序。我有一个存储在核心数据中的练习列表,当用户从列表中选择一个练习时,我会将其添加到状态中的数组中。

@State private var workoutExercises: [CDWorkoutExercise] = []

...

func onSelectExercise(exercise: CDExercise) {
    let newWorkoutExercise = CDWorkoutExercise(context: self.moc)
    newWorkoutExercise.exercise = exercise
    newWorkoutExercise.reps = 8
    newWorkoutExercise.sets = 3

    workoutExercises.append(newWorkoutExercise)
}

我有一个 ForEach,它循环已添加到数组中的练习核心数据对象,并显示它们添加的练习,并允许用户使用输入(最好是步进器或文本字段)来更改要执行的重复次数为了练习。

ForEach(workoutExercises, id: \.self) { workoutExercise in
    VStack {
        Text(workoutExercise.exercise?.wrappedName ?? "Unknown")

        Stepper("Reps", value: $workoutExercise.reps, in: 1...100)
    }
}

但是,当我尝试将对象绑定到输入时,Xcode 显示错误Use of unresolved identifier: $workoutExercise(在本例中是在定义步进器的行上),我不确定如何解决问题或哪里出了问题。


如果我正确理解你的意图和你的模型,以下应该有效

TextField("", text: Binding<String>(
    get: {workoutExercise.exercise?.wrappedName ?? "Unknown"}, 
    set: {workoutExercise.exercise?.wrappedName = $0}))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将核心数据对象绑定到输入 SwiftUI 的相关文章

随机推荐