Created
October 30, 2024 14:42
-
-
Save moyerr/1b40ea68994e9fc65e76d21866a1dadb to your computer and use it in GitHub Desktop.
A modifier that provides automatic sizing for sheets in SwiftUI (iOS 16+)
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 SelfSizingSheetPresentation: ViewModifier { | |
private enum BoundsPreference: PreferenceKey { | |
static let defaultValue: Anchor<CGRect>? = nil | |
static func reduce(value: inout Value, nextValue: () -> Value) { | |
value = nextValue() | |
} | |
} | |
@State private var sheetHeight: CGFloat = .zero | |
func body(content: Content) -> some View { | |
content | |
.anchorPreference( | |
key: BoundsPreference.self, | |
value: .bounds, | |
transform: { $0 } | |
) | |
.overlayPreferenceValue(BoundsPreference.self) { anchor in | |
GeometryReader { proxy in | |
if let anchor { | |
Color.clear | |
.onChange( | |
of: proxy[anchor].size.height, | |
initial: true | |
) { _, newValue in | |
self.sheetHeight = newValue | |
} | |
} | |
} | |
} | |
.presentationDetents([.height(sheetHeight)]) | |
} | |
} | |
extension View { | |
func selfSizingSheetPresentation() -> some View { | |
modifier(SelfSizingSheetPresentation()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment