Skip to content

Instantly share code, notes, and snippets.

@natpenguin
Created July 25, 2022 07:15
Show Gist options
  • Save natpenguin/9f13ee586d5b9cf13d67ad1e5af8c64f to your computer and use it in GitHub Desktop.
Save natpenguin/9f13ee586d5b9cf13d67ad1e5af8c64f to your computer and use it in GitHub Desktop.
Applying child view size to parent view
import SwiftUI
struct SizePreferenceKey: PreferenceKey {
static var defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
struct SizeCompatibleNavigationView<Content: View>: View {
@ViewBuilder var content: () -> Content
@State private var bounds: CGSize = .zero
var body: some View {
NavigationView {
content()
.background(
GeometryReader { geo in
Color.clear
.preference(key: SizePreferenceKey.self, value: geo.size)
}
)
}
.frame(width: bounds.width, height: bounds.height)
.onPreferenceChange(SizePreferenceKey.self) { bounds in
self.bounds = bounds
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment