Get height of a view inside ZStack in SwiftUI

71 views Asked by At

I'm trying to get the height of a popup view that I added in my main content view. I tried using geometry reader, but it seems to be returning full height of the view. Am I doing something wrong here?

import SwiftUI

struct ContentView: View {
    var body: some View {
        ZStack(alignment: .top) {
            GeometryReader { geometry in
                let rect = geometry.frame(in: .named("popup"))
                TestPopupView(message: "Popup height is \(geometry.size.height)-\(rect.height)")
                    .coordinateSpace(name: "popup")
            }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

struct TestPopupView: View {
    
    var message = "Test popup"
    var body: some View {
            VStack(spacing: 0) {
                VStack {
                    Text(message)
                        .multilineTextAlignment(.center)
                        .foregroundColor(.white)
                        .padding()
                    
                }.background(Color.black)
                    .clipShape(RoundedRectangle(cornerRadius: 10))
            }
            .frame(maxWidth: 235)
            .frame(minHeight: 90)
    }
}

This is the result it displays, which is obviously incorrect.

enter image description here

0

There are 0 answers