SwiftUI - 在不修改视图大小的情况下使用 GeometryReader [英] SwiftUI - Using GeometryReader Without Modifying The View Size
问题描述
我有一个标题视图,它使用 edgesIgnoringSafeArea
将其背景扩展到状态栏下方.要正确对齐标题视图的内容/子视图,我需要 GeometryReader
中的 safeAreaInsets
.但是,当使用 GeometryReader
时,我的视图不再具有合适的尺寸.
I have a header view which extends its background to be under the status bar using edgesIgnoringSafeArea
. To align the content/subviews of the header view correctly, I need the safeAreaInsets
from GeometryReader
. However, when using GeometryReader
, my view doesn't have a fitted size anymore.
不使用GeometryReader
struct MyView : View {
var body: some View {
VStack(alignment: .leading) {
CustomView()
}
.padding(.horizontal)
.padding(.bottom, 64)
.background(Color.blue)
}
}
预览
使用GeometryReader
struct MyView : View {
var body: some View {
GeometryReader { geometry in
VStack(alignment: .leading) {
CustomView()
}
.padding(.horizontal)
.padding(.top, geometry.safeAreaInsets.top)
.padding(.bottom, 64)
.background(Color.blue)
.fixedSize()
}
}
}
预览
有没有办法在不修改底层视图大小的情况下使用GeometryReader
?
Is there a way to use GeometryReader
without modifying the underlying view size?
推荐答案
我设法通过将页面主视图包装在 GeometryReader
中并传递 safeAreaInsets
来解决这个问题到 MyView
.由于它是我们想要整个屏幕的主页面视图,因此可以尽可能贪婪.
I managed to solve this by wrapping the page main view inside a GeometryReader
and pass down the safeAreaInsets
to MyView
. Since it is the main page view where we want the entire screen thus it is ok to be as greedy as possible.
这篇关于SwiftUI - 在不修改视图大小的情况下使用 GeometryReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!