tHatpart
tHatpart

Reputation: 1146

HStack leading and trailing spacing in SwiftUI

How can you add equal leading/trailing spacing to a scrollable HStack in SwiftUI? In this example there is spacing between the cells, but not in the first cell's leading or the last cell's trailing

I've tried adding horizontal spacing to the ForEach but that also spaces the cells, which is not what I want. I want equal spacing between the cells and the leading and trailing of the first and last cell in the loop

struct ContentView: View {
    var body: some View {
        ScrollView(.horizontal) {
            HStack(spacing: 5) {
                ForEach(0...1, id: \.self) {_ in
                    Capsule(style: .circular)
                        .background(Color.red)
                        .frame(width: 250, height: 40, alignment: .center)
                }
            }
        }
    }
}

enter image description here

Upvotes: 0

Views: 3620

Answers (1)

ScottM
ScottM

Reputation: 10512

Add horizontal padding to the HStack

HStack(spacing: 5) {
  ForEach(0...1, id: \.self) {_ in
    // etc
  }
}
.padding(.horizontal, 5)

NB: .horizontal is a shortcut way of setting padding for both the leading and trailing edges at the same time – so .padding([.leading, .trailing], 5) is equivalent.

Upvotes: 4

Related Questions