这是我的代码,我想做的是创建按钮并将文本设置为数组中其对应的值,然后在点按它们时将值增加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()
}
}
答案 0 :(得分:0)
for
或ForEach
构造需要一个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)
}
}
}
}
}