George Baker
George Baker

Reputation: 91

How To Create a Specific Number of SwiftUI Shapes

I want to know how to dynamically create multiple SwiftUI shapes (e.g. Rectangles).

How does one go from something like this:

struct ContentView: View {
    var body: some View {
        Rectangle()
            .fill(Color.blue)
            .frame(width: 100, height: 100)
    }
}

To something like this:

struct ContentView: View {
    var body: some View {
        VStack {
            for index 1...10 {
                Rectangle()
                    .fill(Color.black)
                    .frame(width:100, height: 100)
            }
        }
    }
}

Upvotes: 0

Views: 288

Answers (1)

George
George

Reputation: 30361

You can use SwiftUI's ForEach view by providing a range:

struct ContentView: View {

    var body: some View {
        VStack {
            ForEach(0 ..< 10) { _ in
                Rectangle()
                    .fill(Color.black)
                    .frame(width:100, height: 100)
            }
        }
    }
}

Upvotes: 1

Related Questions