0

如何从另一个视图访问视图的大小?

为了获得“ Hello world! ”文本的高度,我附上了.background()一个GeometryReader。现在,我只是使用打印高度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!??? ”的高度替换。我怎样才能做到这一点?

4

1 回答 1

1

你可以:

  1. 创建一个@State属性来存储高度
  2. 使用.onAppear {附加到设置它Color.clear
  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)") 
        }
    }
}

结果:

于 2021-04-25T19:34:58.967 回答