Last active
May 30, 2020 20:33
-
-
Save jhowlin/643d052701f054b69e95e2e8735b7eff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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