首页 > 解决方案 > Use data to define amount of objects in Array

问题描述

I'm working on a checklist in SwiftUI and want to define the amount of checkboxes in my data. So for example, in case of fruit, the user should tick 3 checkboxes whereas water requires more checks because you need to drink more glasses of water a day.

I'm using "for each" in a HStack to make an array of checkboxes:

 HStack {
           ForEach(0 ..< 3) { index in
           VStack {
               Button(action: {
                  self.checked[index].toggle()
                                    })

I want to replace the ( 0..<3) with checklist.steps which is where the amount (INT) is defined.

let checklistData = [
    Checklist(title: "Fruit", instruction: "1 vakje = 1 stuk of 100g", steps: Int(4)),

Is there a way to define the amount of checkboxes in my data?

Thanks in advance <3

Solution

The following code worked for me:

HStack {
           ForEach(0 ..< checklist.steps) { index in
           VStack {
               Button(action: {
                  self.checked[index].toggle()
                                    })

标签: swiftswiftui

解决方案


我不确定你是否想要这个?

HStack {
       ForEach(0 ..< checklistData[x].steps) { index in
       VStack {
           Button(action: {
              self.checked[index].toggle()
                                })

推荐阅读