簡體   English   中英

SwiftUI - 如何從不同的視圖中獲取 GeometryReader 大小/高度?

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

如何從另一個視圖訪問視圖的大小?

為了獲得“ Hello world! ”文本的高度,我將GeometryReader.background()附加到它上面。 現在,我只是使用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 ???")
        }
    }
}

結果:

“你好世界!”上面的“第一個文本的高度是???”

我現在想換??? 與“ Hello world! ”的高度。 我怎樣才能做到這一點?

你可以:

  1. 創建一個@State屬性來存儲高度
  2. 使用附加到Color.clear.onAppear {設置它
  3. ??? \(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)") 
        }
    }
}

結果:

“你好世界!”上面“第一個文本的高度是 20.333333”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM