我不明白为什么在使用ForEach
时VStack
内ScrollView
内的GeometryReader
内的元素之间会有多余的垂直间距呈现自定义的水平分隔线。
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)
}
}
使用.frame(maxHeight: 1)
,蓝色填充消失了,但是连续的HStack
之间仍然有空白。
我希望垂直间距在此图像中类似,即0。此图像是通过取消注释Text("test")
源并注释GeometryReader
代码来实现的。
我正在使用Xcode 11.3.1 (11C504)
答案 0 :(得分:9)
如果我了解您的最终目标,那就是使每行上方都用虚线包围,并且它们之间没有填充,就像这样:
在这种情况下,IMO应该将这些行放在背景中。例如:
ScrollView {
VStack(alignment: .leading) {
ForEach(self.elements, id: \.self) { element in
HStack {
Text("\(element.index+1)")
.font(.system(.caption, design: .rounded))
.frame(width: 32, alignment: .trailing)
Text(element.element)
.font(.system(.caption, design: .monospaced))
Spacer()
}
.background(
ZStack(alignment: .top) {
Color.green
GeometryReader { geometry in
Path { path in
path.move(to: .zero)
path.addLine(to: CGPoint(x: geometry.size.width, y: 0))
}
.strokedPath(StrokeStyle(lineWidth: 1, dash: [1,2]))
.foregroundColor(Color.red)
}
}
)
}
}
}
关键点在于ScrollView不是垂直堆叠容器。它只是获取其内容并使它可滚动。它在代码中的内容是ForEach,它会生成视图;它并不是真的打算将它们布置出来。因此,当您将ScrollView与ForEach结合使用时,实际上并没有真正负责按照您想要的方式放置视图。要垂直堆叠视图,您需要一个VStack。
您也可以将其应用于您的结构,但是添加另一个VStack,并获得相同的结果:
ScrollView {
VStack(spacing: 0) { // <---
ForEach(self.elements, id: \.self) { element in
VStack(alignment: .leading, spacing: 0) {
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]))
}
.foregroundColor(.red)
.frame(height: 1)
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()
}
}
.background(Color.green) // <-- Moved
}
}
}