【问题标题】:SwiftUi : for i in 0... How to solve closure containing control flow statementSwiftUi:for i in 0 ... 如何解决包含控制流语句的闭包
【发布时间】:2019-11-07 13:10:37
【问题描述】:

我尝试显示一些取决于整数的图像。

以'3'为例,我想要那个:

VStack {
     Text(recette.name)
     HStack() {
           Text("Durée 20 min")
             .font(.caption)
             .fontWeight(.light)
           Text("Notes")
             .font(.caption)
             .fontWeight(.light)
           HStack(spacing: -1.0) {
                for 0 in 0...recette.avis{
                      Image(systemName: "star.fill")
                        .padding(.leading)
                        .imageScale(.small)
                        .foregroundColor(.yellow)
                 }
            }
     }
}

但代码在 for 中无法编译并出现此错误。

包含控制流语句的闭包不能与函数生成器“ViewBuilder”一起使用

有人可以帮我吗?

谢谢。

【问题讨论】:

标签: swift swiftui swiftui-list


【解决方案1】:

您想使用ForEach 来创建您的星星。

下面是一个工作示例。

// This is a simple struct to mock the data
struct Recette {
    let name: String = "Test"
    let avis: Int = 3
}

struct ContentView: View {

    let recette = Recette()

    var body: some View {
        VStack {
            Text(recette.name)
            HStack() {
                Text("Durée 20 min")
                    .font(.caption)
                    .fontWeight(.light)
                Text("Notes")
                    .font(.caption)
                    .fontWeight(.light)
                HStack(spacing: -1.0) {
                    ForEach(0..<recette.avis) {_ in // <- use ForEach() here
                        Image(systemName: "star.fill")
                            .padding(.leading)
                            .imageScale(.small)
                            .foregroundColor(.yellow)
                    }

                }
            }
        }
    }
}

这是上面代码产生的结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多