SwiftUI,列表视图中项目的唯一步进器

时间:2019-12-07 23:13:48

标签: swiftui

我想显示从NSManagedObject获取的数组的列表。 然后在该列表中为每个项目设置一个步进器,最终将使递增的数量与NSManagedObject的属性相同。

到目前为止,我的代码:

struct ExtraIncomeAdviceView: View {

    var incomes:FetchedResults<Income>
    var savingsGoals:FetchedResults<SavingsGoal>
    var presentationModeAddIncomeView: Binding<PresentationMode>
    @Environment(\.presentationMode) var presentationModeAdvice: Binding<PresentationMode>
    @State private var increment:Int = 0

    var body: some View {
        VStack{

            Text("So you got an extra £\(String(format: "%0.2f",getLatestExtraIncome()))?").font(.headline)
            VStack{
                HStack{
                    Text("For your goals, set aside:").font(.footnote).foregroundColor(.gray)
                    Spacer()
                }
                ForEach(self.savingsGoals) { goal in

                    HStack{
                        Spacer()
                        Stepper("Add to \(goal.name!): \(goal.progressAmount!)", onIncrement: {
                            self.increment += 1
                            print("Adding to age")
                        }, onDecrement: {
                            self.increment -= 1
                            print("Subtracting from age")
                        })

                    }

                }

            }.padding()
                .padding(.vertical, 40)
            Button(action:  {


                self.presentationModeAdvice.wrappedValue.dismiss()
                self.presentationModeAddIncomeView.wrappedValue.dismiss()
            }) {
                Text("Got it!")
                    .foregroundColor(.white)

                    .padding(15)
                    .background(Color .orange)
                    .cornerRadius(40)
            }

        }.padding()
    }
}

问题是,ForEach中显示的每个目标都读取和写入相同的变量。我被困在如何动态创建新变量以读取和写入数组中每个项目的问题上。

1 个答案:

答案 0 :(得分:1)

在您的情况下,我将创建一个自定义视图结构,该结构在名为ForEach的{​​{1}}内调用,或者包含HStack,Stepper和局部增量变量的适用对象。然后,您可以在GoalRow()结构中适当地处理步进值,并稍微清理代码。

GoalRow()

,然后在ForEach(self.savingsGoals) { goal in GoalRow(goal: goal) } 内:

GoalRow

Apple在其教程中提到了这一点。请参阅本教程Building Lists and Navigation

中的struct GoalRow: View { var goal: YourObject @State private var increment: Int = 0 var body: some View { HStack(alignment: .leading, spacing: 20) { Stepper("Add to \(goal.name!): \(goal.progressAmount!)", onIncrement: { self.increment += 1 // edit your proposed progress amount here print("Adding to age") }, onDecrement: { self.increment -= 1 // edit your proposed progress amount here print("Subtracting from age") }) } 示例