Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI | VStack won't work inside of ForEach Loops

I'm using a ForEach loop to display different bars with numbers underneath them to display a graph. However, I can't seem to use a VStack inside of the ForEach loop inside of an HStack to display multiple bars next to each other, all with a number underneath.

HStack{
    ForEach(0 ..< 7) {
        VStack {
            Capsule().frame(width: 30, height: 200)
            Text("\($0 + 1)")
        }                        
    }
}

I've tried using moving the VStack outside of the ForEach loop but this results in the bars being displayed below each other. How can I display the number underneath the bar whilst arranging the multiple bars next to each other?

like image 826
Diego Gonzalez Avatar asked Nov 29 '25 08:11

Diego Gonzalez


1 Answers

It works with small fix - added explicit parameter for ForEach. Tested with Xcode 12.1 / iOS 14.1

demo

HStack {
    ForEach(0 ..< 7) { i in
        VStack {
            Capsule().frame(width: 30, height: 200)
            Text("\(i + 1)")
        }
    }
}
like image 127
Asperi Avatar answered Dec 02 '25 04:12

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!