Created
August 21, 2025 23:31
-
-
Save dan-hart/a7dbea9f5bcda1e26464395473410cce to your computer and use it in GitHub Desktop.
GeometryReader alternative called onGeometryChanged
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 ContentView: View { | |
| @State private var contentHeight: CGFloat = 0 | |
| @State private var showsSheet = false | |
| @State private var fontSize: CGFloat = 50 | |
| var body: some View { | |
| VStack(spacing: 20) { | |
| Text("onGeometryChange example") | |
| .font(.largeTitle) | |
| .multilineTextAlignment(.center) | |
| Button { | |
| fontSize = CGFloat.random(in: 30...80) | |
| showsSheet = true | |
| } label: { | |
| Text("Show sheet") | |
| } | |
| .buttonStyle(.bordered) | |
| } | |
| .padding() | |
| .sheet(isPresented: $showsSheet) { | |
| VStack { | |
| Text("As you can see this sheet is dynamically sized to fit this content.") | |
| .fixedSize(horizontal: false, vertical: true) | |
| .padding() | |
| .font(.system(size: fontSize)) | |
| } | |
| .onGeometryChange(for: CGSize.self) { proxy in | |
| proxy.size | |
| } action: { | |
| self.contentHeight = $0.height | |
| // Alternatively you can get the `width` here | |
| } | |
| .presentationDetents([.height(contentHeight)]) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment