swift - 如何在 SwiftUI 中为演示文稿定位器调整内容大小

标签 swift swiftui ios16

我可以像这样在 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/

相关文章:

swift - 如何从 Swift 3 (XCode 8) 中的文本文件中读取数据

ios - 禁用 SwiftUI 应用程序的 iTunesStore 访问 - 摆脱 "Error retrieving iTunesStore accounts"警告

iOS 16 更改蓝牙 LE 连接间隔

swift - 将 UIEditMenuInteraction 与 UITextView 结合使用

swift - 如何在 ForEach Swiftui 中的结构列表中使用枚举?

ios - 过渡动画在 iOS 16 中不起作用,但在 iOS 15 中起作用

swift - 可选绑定(bind),这里的 "Binding"这个词到底是什么意思?

ios - 在 iOS 中向 TableView 单元格添加虚线底部边框与文本随机重叠

swift - 将 "if let"与逻辑 "or"运算符一起使用

ios - 使用 DragGesture 调整 SwiftUI View 的框架会在所有维度上调整其大小