如何在 SwiftUI 中调整显示制动器的内容大小

Ber*_*lue 5 swift swiftui ios16

我可以在 SwiftUI 中显示具有自定义高度和棘爪的工作表,如下所示。

.sheet(isPresented: $showSheet) {
    MySheet()
        presentationDetents([.height(500), .large])
}
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以测量我的视图的准确高度MySheet并将其传递给presentationDetents没有固定值的?我问这个问题是因为根据用户的辅助功能设置,视图的高度可能会发生变化。

use*_*037 21

方法:

  • 测量所呈现内容的大小并将该值设置到 @State 变量中
  • 在所呈现的内容的背景中使用GeometryReader来测量内容的高度。
  • GeometryReader添加到所呈现内容的背景而不是前景,因为GeometryReader往往会扩展到为其提供的所有空间,例如颜色或形状。

笔记:

  • 这是一种粗略的方法,很高兴听到任何更好的方法
  • 对于多行文本,请添加.fixedSize(horizontal: false, vertical: true)到文本中

代码

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
                        .task {
                            print("size = \(proxy.size.height)")
                            sheetContentHeight = proxy.size.height
                        }
                }
            }
            .presentationDetents([.height(sheetContentHeight)])
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于多行文本,将“.fixedSize(horizo​​ntal: false, Vertical: true)”添加到“Text”,以便它可以垂直增长 (3认同)