![](/img/trans.png)
[英]SwiftUI erroneous vertical alignment of overlay when using GeometryReader
[英]Alignment changes after adding a GeometryReader
我有一个基本上看起来像这样的布局:
ZStack(alignment: .bottom) {
GeometryReader { geometry in
ZStack {
Text("Centered")
}
.frame(width: geometry.size.width, height: geometry.size.height, alignment: .center)
.background(Color.red)
}
Group {
GeometryReader { geometry in // This GeometryReader is causing issues.
VStack {
Text("I want this at the bottom")
}
.frame(width: geometry.size.width, height: nil, alignment: .topLeading)
}
}
}
呈现时,两个 Text 元素都呈现在屏幕中央。 第二个文本元素的容器占据了屏幕的整个宽度,这是预期的。 如果我删除有问题的 GeometryReader,则文本会在屏幕底部正确呈现,但显然框架未设置为屏幕的整个宽度。 为什么会这样?
默认情况下,SwiftUI 容器对内容很紧,但GeometryReader
消耗最大的可用空间。 因此,如果要删除第二个GeometryReader
, VStack
只会包装内部Text
。
如果仍然需要保留第二个GeometryReader
(读取width
)并将文本放在底部,最简单的方法是添加Spacer
如下
Group {
GeometryReader { geometry in
VStack {
Spacer()
Text("I want this at the bottom")
}
.frame(width: geometry.size.width, height: nil, alignment: .topLeading)
}
}
如何在底部粘贴视图的替代方法,您可以在我在这篇文章中的答案中找到不使用间隔器的位置视图底部
这个怎么样?
struct ContentView: View {
var body: some View {
ZStack(alignment: .bottom) {
GeometryReader {geometry in
Text("Centered")
.frame(width: geometry.size.width, height: geometry.size.height)
.background(Color.red)
}
WidthReader {w in
Text("I want this at the bottom").frame(width: w)
}
}
}
}
struct WidthReader<Content: View>: View {
let widthContent: (CGFloat) -> Content
@State private var width: CGFloat = 0
@State private var height: CGFloat = 0
var body: some View {
GeometryReader {g in
widthContent(width).background(
GeometryReader {g1 in
Spacer().onAppear {height = g1.size.height}.onChange(of: g1.size.height, perform: {height = $0})
}
).onAppear {width = g.size.width}.onChange(of: g.size.width, perform: {width = $0})
}.frame(height: height)
}
}
最简单的方法是将.fixedSize()
修饰符添加到Stack
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.