Measuring Computed View Size

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 MyView : 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?

Replies

If you want to render it on-screen, you could do something like tacking on:


// ...
.background(Color.red)
.overlay(
  GeometryReader { g in
    Text(...) // use g.size
}


Or if you feel like making your brain hurt:


    var body: some View {
        GeometryReader { g in
            Text("\(g.size.width)") // The size of what?
                .font(.title)
                .foregroundColor(.white)
                .padding()
                .background(Color.red)
                .fixedSize()
        }
    }


(The "Building Custom Views..." session is fantastic, but I'm _really_ looking forward to more documentation about the layout process...)

I don't believe joav understood your question correctly. I found one solution and posted it here: https://forums.developer.apple.com/thread/118261


Have you found any better method?