如何解决GeometryReader 高度因子视图类型而异
我想在 VStack
内均匀分布任意视图。为此,我将 VStack
包裹在 GeometryReader
中。此时,我将 VStack
的孩子的高度设置为任意高度(在我的例子中为 10)并计算偏移量。这对 Text
类型的子项按预期工作。
GeometryReader { proxy in
VStack {
ForEach(0..<5) { element in
Text("\(element)")
.offset(y: proxy.size.height / 4 * CGFloat(element) - CGFloat(Double(element) + 0.5) * frameHeight)
.frame(height: frameHeight)
}
}
}
但是,如果我想使用其他视图(例如颜色或矩形)实现相同的效果,则需要手动将 GeometryReader
的高度减去 32。视图的默认填充似乎是 16,但我还没有设置填充,Text
视图也不是这样。
GeometryReader { proxy in
VStack {
ForEach(0..<5) { element in
Color.red
.offset(y: (proxy.size.height - 32) / 4 * CGFloat(element) - CGFloat(Double(element) + 0.5) * frameHeight)
.frame(height: frameHeight)
}
}
}
谁能向我解释为什么会这样?这只是一个简化示例,在我的项目中,我使用 ViewBuilder
动态提供子视图。
解决方法
你应该使用间距:
GeometryReader { proxy in
VStack(spacing: 0.0) { // <<: Here!
ForEach(0..<5) { element in
Color.red
.offset(y: (proxy.size.height - 32) / 4 * CGFloat(element) - CGFloat(Double(element) + 0.5) * frameHeight)
.frame(height: frameHeight)
}
}
.position(x: proxy.size.width/2,y: proxy.size.height/2) // <<: this will Center your View!
}
.ignoresSafeArea() // <<: this will make your View Full Screen!