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)
}
}
}
}
}
CodePudding user response:
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.