1

How can I access the size of a View from another View?

To get the height of the "Hello world!" text, I attached a .background() of GeometryReader to it. For now, I'm just printing the height using let _ = print(proxy.size.height).

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello world!")
                .background(
                    GeometryReader { proxy in
                        Color.clear /// placeholder
                        let _ = print(proxy.size.height) /// 20.333333333333332
                    }
                )
            
            Text("Height of first text is ???")
        }
    }
}

Result:

"Hello world!" above "Height of first text is ???"

I now want to replace ??? with the height of the "Hello world!". How can I do this?

1

1 Answer 1

6

You can:

  1. Make a @State property to store the height
  2. Set it using an .onAppear { attached to Color.clear
  3. Replace ??? with \(textHeight)
struct ContentView: View {
    @State var textHeight = CGFloat(0) /// 1.

    var body: some View {
        VStack {
            Text("Hello world!")
                .background(
                    GeometryReader { proxy in
                        Color.clear
                            .onAppear { /// 2.
                                textHeight = proxy.size.height
                            }
                    }
                )
                                          /// 3.
            Text("Height of first text is \(textHeight)") 
        }
    }
}

Result:

"Hello world!" above "Height of first text is 20.333333"

Sign up to request clarification or add additional context in comments.

2 Comments

onAppear is only called when it appears, so it doesn't handle orientation changes.
I spoke to an Apple engineer during WWDC21 and they said that to handle orientation, attach a .onChange.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.