这是我的代码,我想要做的是创建按钮并将文本设置为数组中相应的值,然后在点击按钮时将值增加 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()
}
}
最佳答案
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)
}
}
}
}
}
关于ios - 如何迭代数组来初始化按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58904359/