测量 SwiftUI 视图的渲染大小? [英] Measure the rendered size of a SwiftUI view?

查看:18
本文介绍了测量 SwiftUI 视图的渲染大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法在 SwiftUI 运行其视图渲染阶段后测量视图的计算大小?例如,给定以下视图:

Is there a way to measure the computed size of a view after SwiftUI runs its view rendering phase? For example, given the following view:

struct Foo : View {
    var body: some View {
        Text("Hello World!")
            .font(.title)
            .foregroundColor(.white)
            .padding()
            .background(Color.red)
    }
}

选择视图后,计算出的大小显示在左下角的预览画布中.有谁知道在代码中访问该大小的方法?

With the view selected, the computed size is displayed In the preview canvas in the bottom left corner. Does anyone know of a way to get access to that size in code?

推荐答案

打印值很好,但能够在父视图(或其他地方)中使用它们更好.所以我又进一步详细说明了它.

Printing out values is good, but being able to use them inside the parent view (or elsewhere) is better. So I took one more step to elaborate it.

struct GeometryGetter: View {
    @Binding var rect: CGRect

    var body: some View {
        GeometryReader { (g) -> Path in
            print("width: \(g.size.width), height: \(g.size.height)")
            DispatchQueue.main.async { // avoids warning: 'Modifying state during view update.' Doesn't look very reliable, but works.
                self.rect = g.frame(in: .global)
            }
            return Path() // could be some other dummy view
        }
    }
}

struct ContentView: View {
    @State private var rect1: CGRect = CGRect()
    var body: some View {
        HStack {
            // make to texts equal width, for example
            // this is not a good way to achieve this, just for demo
            Text("Long text").background(Color.blue).background(GeometryGetter(rect: $rect1))
            // You can then use rect in other places of your view:
            Text("text").frame(width: rect1.width, height: rect1.height).background(Color.green)
            Text("text").background(Color.yellow)
        }
    }
}

这篇关于测量 SwiftUI 视图的渲染大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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