我可以像这样在 SwiftUI 中显示带有制动器的自定义高度的工作表。
.sheet(isPresented: $showSheet) {
MySheet()
presentationDetents([.height(500), .large])
}
有没有一种方法可以测量我的 View MySheet
的确切高度并将其传递给 presentationDetents
而无需固定值?我问是因为根据用户的辅助功能设置, View 的高度可能会改变。
最佳答案
方法:
- 测量所呈现内容的大小并将值设置到@State 变量中
- 在呈现内容的背景中使用
GeometryReader
来测量内容的高度。 GeometryReader
被添加到正在呈现的内容的背景中,而不是前景中,因为GeometryReader
倾向于扩展到给定它的所有空间,例如颜色或形状。
注意事项:
- 这是一种粗略的方法,很高兴听到任何更好的方法
代码
struct ContentView: View {
@State private var isSheetShown = false
@State private var sheetContentHeight = CGFloat(0)
var body: some View {
Button("Show sheet") {
isSheetShown = true
}
.sheet(isPresented: $isSheetShown) {
VStack {
Text("hello line 1")
Text("hello line 2")
Text("hello line 3")
}
.background {
//This is done in the background otherwise GeometryReader tends to expand to all the space given to it like color or shape.
GeometryReader { proxy in
Color.clear
.onAppear {
print("size = \(proxy.size.height)")
sheetContentHeight = proxy.size.height
}
}
}
.presentationDetents([.height(sheetContentHeight)])
}
}
}
关于swift - 如何在 SwiftUI 中为演示文稿定位器调整内容大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74423799/