SwiftUi:对于0中的i ...如何解决包含控制流语句的闭包

我尝试显示一些依赖于整数的图像。

以'3'为例,我想要

Constraints and Properties

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”一起使用

有人可以帮助我吗?

谢谢。

a277158272 回答:SwiftUi:对于0中的i ...如何解决包含控制流语句的闭包

您想使用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)
                    }

                }
            }
        }
    }
}

这是上面的代码产生的:

What code produces

本文链接:https://www.f2er.com/3144599.html

大家都在问