SwiftUI 中的几何阅读器是什么? [英] What is Geometry Reader in SwiftUI?

查看:22
本文介绍了SwiftUI 中的几何阅读器是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am learning SwiftUI. And I come across to "GeometryReader". And I want to know why and when to use it?

推荐答案

UPDATE

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

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

GeometryReader is a view that gives you access to the size and position of it's parent. For example:

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() 结合起来以获得一些其他视图的边界.例如,文本视图很难提前预测它的大小.当我需要这些信息时,我会使用这个技巧:

I usually combine it with .background() to obtain some other view's bounds. For example, The Text view is hard to predict how large it would be in advance. When I need that information, I use this trick:

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

First I have defined a view called GeometryGetter:

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)
    }
}

然后,获取文本视图(或任何其他视图)的边界:

Then, to get the bounds of a Text view (or any other 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 的其他问题的答案.看看它们:

For some use cases, I posted some answers to other questions that use GeometryReader. Check them out:

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

Move textfields to avoid being hidden by the keyboard: https://stackoverflow.com/a/56721268/7786555

如何在 SwiftUI 中设置另一个视图的大小:https://stackoverflow.com/a/56661706/7786555

How to make view the size of another view in SwiftUI: https://stackoverflow.com/a/56661706/7786555

注意

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

In GeometryGetter, I added a DispatchQueue.main.async {} to set the rect. In some cases it could lead to runtime warning otherwise: Modifying state during view update.

这篇关于SwiftUI 中的几何阅读器是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆