Search code examples
swiftswiftuivstackhstack

Remove spacing between HStacks embedded in Stack


I am trying to stack two HStacks filled with circles, however, no matter what I do, I cannot get rid of the spacing between the two.

 VStack {
            VStack(spacing: 0) {
                HStack {
                    ForEach(viewModel.lights) { light in
                        Circle()
                            .foregroundColor(light.color)
                    }
                }
                HStack {
                    ForEach(viewModel.lights) { light in
                        Circle()
                            .foregroundColor(light.color)
                    }
                }
            } .padding()
            
            Button(action: viewModel.start ) {
                Text("Start")
            }
}

What view currently draws as. Want the two HStacks to be much closer together.


Solution

  • Since the Circles have no height constraint, they are taking up all of their available vertical space, even though the visible shape doesn't take up that space. Horizontally, they're limited by the width of the device/screen.

    You can add .aspectRatio(contentMode: .fit) to make them constrained vertically as well to only the space they need to take up:

    Circle()
       .aspectRatio(contentMode: .fit)
       .foregroundColor(light.color)
    

    Once that is done, if you also want to push them towards the top of the screen, you can add a Spacer below the HStacks.