【问题标题】:How to iterate over an array to initialize a button?如何遍历数组以初始化按钮?
【发布时间】:2020-03-13 05:17:19
【问题描述】:

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

【问题讨论】:

  • 我也尝试过 ForEach(0 ..

标签: ios arrays xcode button swiftui


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2011-11-19
    • 2017-11-27
    • 1970-01-01
    • 2021-12-02
    • 2019-08-07
    • 1970-01-01
    相关资源
    最近更新 更多