在我的 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)
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
我想要的:
感谢您的帮助。
Meg*_*ind 11
以下是使用 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()
}
}
Run Code Online (Sandbox Code Playgroud)
Pro*_*in8 -1
我认为你使用GeometryReader
. 您是否尝试过仅使用 a Spacer()
?
struct ContentView: View {
var body: some View {
VStack {
Text("Haha")
Spacer()
VStack {
Text("1")
Text("2")
Text("3")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2203 次 |
最近记录: |