在 SwiftUI 中获取 ZStack 内部视图的高度

Get height of a view inside ZStack in SwiftUI

提问人:Francis F 提问时间:11/14/2023 更新时间:11/14/2023 访问量:28

问:

我正在尝试获取我在主内容视图中添加的弹出视图的高度。我尝试使用几何阅读器,但它似乎返回了视图的全高。我在这里做错了什么吗?

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)
    }
}

这是它显示的结果,这显然是不正确的。

enter image description here

SwiftUI Swift5 iOS14 XCode15 GeometryReader

评论

0赞 Sweeper 11/14/2023
这感觉像是一个 XY 问题。为什么,你想知道视图的高度吗?
0赞 Baffo rasta 11/14/2023
@FrancisF:看看这个

答: 暂无答案