在我的SwiftUI应用程序中,我有一个VStack(VStack 1)容器,可以全屏显示高度。在此VStack中,我有另一个VStack(VStack 2),它根据其子级(文本)获得高度,我想将其放在该父级(VStack 1)的底部。在VStack 2上,我需要放置GeometryReader以获取VStack的高度(VStack 2)。问题是GeometryReader自动获得全屏高度。因此,VStack 2放置在屏幕中间。不是我想要的我不知道是否可以将GeometryReader的高度设置为与VStack 2相同的高度?
我的测试代码:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
GeometryReader { geometry in
VStack {
Text("Text n°1")
Text("Text n°2")
Text("Text n°3")
Text("Text n°4")
}
.border(Color(.red))
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: nil, alignment: .bottom)
.border(Color(.black))
}
.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .bottom)
}
}
结果:
我想要的
谢谢您的帮助。
答案 0 :(得分:1)
我认为您使用GeometryReader
使其过于复杂。您是否尝试过仅使用Spacer()
?
struct ContentView: View {
var body: some View {
VStack {
Text("Haha")
Spacer()
VStack {
Text("1")
Text("2")
Text("3")
}
}
}
}
答案 1 :(得分:1)
以下是在使用GeometryReader时将子视图高度设置为父视图
import SwiftUI
struct ContentView: View {
@State private var totalHeight = CGFloat(100) // no matter - just for static Preview !!
var body: some View {
HStack(alignment:.top) {
Text("Title 1")
GeometryReader { geo in
VStack(spacing: 10) {
Text("Subtitle 1")
.frame(maxWidth: .infinity)
Text("Subtitle 2")
.frame(maxWidth: .infinity)
Text("Subtitle 3")
.frame(maxWidth: .infinity)
}
.background(Color.blue)
.frame(width: geo.size.width * 0.6)
.background(GeometryReader {gp -> Color in
DispatchQueue.main.async {
// update on next cycle with calculated height of ZStack !!!
self.totalHeight = gp.size.height
}
return Color.clear
})
}
.background(Color.yellow)
}
.frame(maxWidth: .infinity)
.frame(height: totalHeight)
.background(Color.green)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}