swift - SwiftUI 中的几何阅读器是什么?

标签 swift swiftui

我正在学习 SwiftUI。我遇到了“GeometryReader”。我想知道为什么以及何时使用它?

最佳答案

更新

自发布答案以来,我还写了一篇关于 GeometryReader 工作原理的文章。查看更详细的解释:https://swiftui-lab.com/geometryreader-to-the-rescue/


GeometryReader 是一个 View ,可让您访问其父级的大小和位置。例如:

struct MyView: View {
    var body: some View {
        GeometryReader { geometry in
           // Here goes your view content,
           // and you can use the geometry variable
           // which contains geometry.size of the parent
           // You also have function to get the bounds
           // of the parent: geometry.frame(in: .global)
        }
    }
}

我通常将它与 .background() 结合使用以获得其他 View 的边界。例如, TextView 很难提前预测它的大小。当我需要这些信息时,我会使用这个技巧:

首先我定义了一个名为 GeometryGetter 的 View :

struct GeometryGetter: View {
    @Binding var rect: CGRect
    
    var body: some View {
        return GeometryReader { geometry in
            self.makeView(geometry: geometry)
        }
    }
    
    func makeView(geometry: GeometryProxy) -> some View {
        DispatchQueue.main.async {
            self.rect = geometry.frame(in: .global)
        }

        return Rectangle().fill(Color.clear)
    }
}

然后,获取 TextView (或任何其他 View )的边界:

struct MyView: View {
    @State private var rect: CGRect = CGRect()

    var body: some View {
        Text("some text").background(GeometryGetter($rect))

        // You can then use rect in other places of your view:
        Rectangle().frame(width: 100, height: rect.height)
    }
}

对于某些用例,我发布了一些使用 GeometryReader 的其他问题的答案。检查它们:

移动文本框以避免被键盘隐藏:https://stackoverflow.com/a/56721268/7786555

如何在 SwiftUI 中使 View 大小与另一个 View 相同: https://stackoverflow.com/a/56661706/7786555

注意

在 GeometryGetter 中,我添加了一个 DispatchQueue.main.async {} 来设置 rect。在某些情况下,它可能会导致运行时警告,否则:在 View 更新期间修改状态

关于swift - SwiftUI 中的几何阅读器是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56729619/

相关文章:

ios - 使所有按钮变圆

ios - UICollectionViewCell 在第一次点击时取消选择预先选择的单元格

ios - 移动谷歌地图但不像优步那样移动标记

ios - SwiftUi:从 WatchKit 的详细 View 中删除 "Back"按钮

ios - 为调用异步请求的函数编写单元测试并且不返回任何内容

swift - 即使调用 Swift SpriteKit 中的 removeFromParent() 按钮仍然有效

swift - SwiftUI 中的 .primary 和 .secondary 颜色是什么?

ios - SwiftUI 动画和后续的反向动画到原始状态

json - 如何在 SwiftUI 中解码来自 API 的 JSON 响应以在 View 中使用

ios - 如何在 SwiftUI 中以横向模式预览设备?