Last active
December 2, 2023 08:59
-
-
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
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
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