Skip to content

Instantly share code, notes, and snippets.

@jhowlin
Last active May 30, 2020 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jhowlin/643d052701f054b69e95e2e8735b7eff to your computer and use it in GitHub Desktop.
Save jhowlin/643d052701f054b69e95e2e8735b7eff to your computer and use it in GitHub Desktop.
struct ChildSize: PreferenceKey {
typealias Value = CGSize
static var defaultValue: Value {
return .zero
}
static func reduce(value: inout Value, nextValue: () -> Value) {
value = nextValue()
}
}
struct Parent: View {
@State var childReqSize: CGSize = .zero
var body: some View {
Child().frame(width:childReqSize.width > 0 ? childReqSize.width : nil, height: childReqSize.height).onPreferenceChange(ChildSize.self) { size in
print(size)
self.childReqSize = size
}
}
}
struct Child: View {
var body: some View {
GeometryReader { proxy in
return Rectangle().preference(key: ChildSize.self, value: self.requiredSizeBasedOnOfferedSize(proxy: proxy))
}
}
func requiredSizeBasedOnOfferedSize(proxy: GeometryProxy) -> CGSize {
// calc size. For instance, we wanted height to be half of width offered by parent...
return CGSize(width: proxy.size.width, height: proxy.size.width / 2)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment