测量SwiftUI视图的渲染大小?

时间:2019-06-14 18:47:03

标签: swiftui

在SwiftUI运行其视图渲染阶段之后,是否有一种方法可以测量视图的计算大小?例如,给出以下视图:

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

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

enter image description here

3 个答案:

答案 0 :(得分:7)

打印出值是好的,但是能够在父视图(或其他视图)中使用它们会更好。所以我又迈出了一步。

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

答案 1 :(得分:5)

您可以使用GeometryReader添加“覆盖”来查看值。但是实际上,最好使用“背景”修饰符并离散处理尺寸值

class OriginalDocument(models.Model):
    document = models.FileField(upload_to='static/original_document', blank=False)
    document_title = models.CharField(max_length=300)
    student_name = models.CharField(max_length=100)
    teacher_name = models.CharField(max_length=100)
    document_type = models.CharField(max_length=100)
    university = models.ForeignKey(University, on_delete=models.CASCADE, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add = True)
    checked_by = CurrentUserField()

    def __str__(self):
        return self.document_title

答案 2 :(得分:0)

这是我想出这一点的丑陋方法:

struct GeometryPrintingView: View {

    var body: some View {
        GeometryReader { geometry in
            return self.makeViewAndPrint(geometry: geometry)
        }
    }

    func makeViewAndPrint(geometry: GeometryProxy) -> Text {
        print(geometry.size)
        return Text("")
    }
}

并更新了Foo版本:

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