Skip to content

Instantly share code, notes, and snippets.

@ralfebert
Last active December 2, 2023 08:59
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 ralfebert/5ce0a2bf91a4a744aaca63755a061183 to your computer and use it in GitHub Desktop.
Save ralfebert/5ce0a2bf91a4a744aaca63755a061183 to your computer and use it in GitHub Desktop.
WidthReaderView: Read the width using a GeometryReader background, pass it out using a PreferenceKey, to be able to compute the height of a view based on the available width
import SwiftUI
struct SizePreferenceKey: PreferenceKey {
static let defaultValue: CGSize = .zero
static func reduce(value: inout CGSize, nextValue: () -> CGSize) {
value = nextValue()
}
}
struct WidthReaderView: View {
@Binding var width: CGFloat
var body: some View {
GeometryReader { geometry in
Color.clear.preference(
key: SizePreferenceKey.self,
value: geometry.size
)
}
.onPreferenceChange(SizePreferenceKey.self) { size in
self.width = size.width
}
}
}
struct WidthReaderExampleView: View {
@State var width : CGFloat = 0
var body: some View {
Text("Hello \(width)")
.frame(height: width / 2)
.background(.yellow)
.background(WidthReaderView(width: $width))
}
}
#Preview {
WidthReaderExampleView()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment