I don't understand why I have extraneous vertical spacing between elements in a ForEach
that is inside a VStack
that is inside a ScrollView
when using a GeometryReader
to render a custom horizontal separator line.
ScrollView {
ForEach(self.model1.elements, id: \.self) { element in
VStack.init(alignment: .leading, spacing: 0) {
// Text("test") // image 3: works correctly
// .background(Color.blue)
GeometryReader { geometry in
Path { path in
path.move(to: .init(x: 0, y: 0))
path.addLine(to: .init(x: geometry.size.width, y: 0))
}
.strokedPath(.init(lineWidth: 1, dash: [1,2]))
}
// .frame(maxHeight: 1) // image 2: uncommenting this line doesn't fix the spacing
.foregroundColor(.red)
.background(Color.blue)
HStack {
Text("\(element.index+1)")
.font(.system(.caption, design: .rounded))
.frame(width: 32, alignment: .trailing)
Text(element.element)
.font(.system(.caption, design: .monospaced))
.frame(maxWidth:nil)
Spacer()
}
.frame(maxWidth:nil)
.background(Color.green)
}
.border(Color.red)
}
}
The above code produces this:
With .frame(maxHeight: 1)
the blue padding is gone, but still there is white space between the consecutive HStack
s.
I want the vertical spacing to be like in this image, ie 0. This image is achieved by uncommenting the Text("test")
source, and commenting the GeometryReader
code.
I'm using Xcode 11.3.1 (11C504)
VStack and HStack already have a default spacing that differs across operating systems and it gets cumbersome using VStack(spacing: 0) { } or HStack(spacing: 0) { } across the views. You can create a handy kind-of syntactic sugar view with zero spacing by default.
SwiftUI lets us set individual padding around views using the padding() modifier, causing views to be placed further away from their neighbors. If you use this with no parameters you'll get system-default padding on all sides, like this: VStack { Text("Using") Text("SwiftUI") .
You need to use . padding modifier for margin. In your code, you have to add padding inside your ScrollView. After that, inside BoxViewTable, you need to add .
The spacing is generated by VStack
.
When creating a VStack
, add the parameter for spacing and set it to 0.
VStack(spacing: 0) {
Element1()
Element2()
Element3()
Element4()
}
VStack
The same spacing property is available for HStack
, LazyVStack
and LazyHStack
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With