5

I want to display some images that depend on an integer.

Example with '3':

enter image description here

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

but the code doesn't compile with this error in for.

Closure containing control flow statement cannot be used with function builder 'ViewBuilder'

Can somebody help me ?

Thank you.

DischordDynne
  • 117
  • 15
MrADOY
  • 123
  • 1
  • 10

1 Answers1

8

You want to use a ForEach so that you can create your stars.

Below is a working example.

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

                }
            }
        }
    }
}

This is what the above code produces:

What code produces

Andrew
  • 26,706
  • 9
  • 85
  • 101