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?

aheze
  • 24,434
  • 8
  • 68
  • 125

1 Answers1

4

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"

aheze
  • 24,434
  • 8
  • 68
  • 125
  • `onAppear` is only called when it appears, so it doesn't handle orientation changes. – aheze May 25 '21 at 22:15
  • 1
    I spoke to an Apple engineer during WWDC21 and they said that to handle orientation, attach a `.onChange`. – aheze Jun 22 '21 at 21:54