SwiftUI - Get size of child?

前端 未结 4 1157
死守一世寂寞
死守一世寂寞 2020-12-15 08:32

Is there any way to get the size of a child view in SwiftUI?

I\'m basically looking to do the UIKit equivalent of:



        
4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 09:04

    Basically, the answer at this point is to use a GeometryReader inside of the child's background(...) modifier.

    // This won't be valid until the first layout pass is complete
    @State var childSize: CGSize = .zero
    
    var body: some View {
        ZStack {
            Text("Hello World!")
                .background(
                    GeometryReader { proxy in
                        Color.clear.
                        .preference(key: SizePreferenceKey.self, value: proxy.size)
                    }
                )
          }
          .onPreferenceChange(SizePreferenceKey.self) { preferences in
              self.childSize = preferences
          }
    }
    
    struct SizePreferenceKey: PreferenceKey {
        typealias Value = CGSize
        static var defaultValue: Value = .zero
    
        static func reduce(value: inout Value, nextValue: () -> Value) {
            value = nextValue()
        }
    }
    

提交回复
热议问题