gpt4 book ai didi

ios - 如何迭代数组来初始化按钮?

转载 作者:行者123 更新时间:2023-11-29 05:18:44 27 4
gpt4 key购买 nike

这是我的代码,我想要做的是创建按钮并将文本设置为数组中相应的值,然后在点击按钮时将值增加 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()
}
}

最佳答案

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)
}
}
}
}
}

关于ios - 如何迭代数组来初始化按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58904359/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com