如何遍历数组以初始化按钮?

时间:2019-11-17 19:29:36

标签: ios arrays xcode button swiftui

这是我的代码,我想做的是创建按钮并将文本设置为数组中其对应的值,然后在点按它们时将值增加1。我目前收到错误消息:“包含封闭的控制流语句不能与函数生成器'ViewBuilder'一起使用”

import SwiftUI
struct ContentView: View {
    @State var counterValues = [0, 0, 0];
    @State var i = 0;
    var body: some View {

        VStack {
            Text("Button Type")

            for i in counterValues.count {
                Button(action: {
                 self.counterValues[i] += 1;

                }) {
                    Text("\(counterValues[i])")
                     .font(.title)
                     .multilineTextAlignment(.center)

                }
                i += 1;
            }


        }


    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

1 个答案:

答案 0 :(得分:0)

forForEach构造需要一个Range-count只是一个Int。因此,您可以说for i in 0..<counterValues.count,但是可以将ForEach与数组的indices属性一起使用以直接获取此范围-

struct ContentView: View {
    @State
    var counterValues = [0,0,0]

    var body: some View {
        VStack {
            ForEach(counterValues.indices) { index in
                Button(action: {
                    self.counterValues[index] += 1
                }) {
                    Text("\(self.counterValues[index])")
                    .font(.title)
                    .multilineTextAlignment(.center)
                }
            }
        }
    }
}