aheze
aheze

Reputation: 30318

SwiftUI - How to get GeometryReader size/height from different View?

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?

Upvotes: 1

Views: 6158

Answers (1)

aheze
aheze

Reputation: 30318

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"

Upvotes: 5

Related Questions