Skip to content

Instantly share code, notes, and snippets.

@moyerr
Created October 30, 2024 14:42
Show Gist options
  • Save moyerr/1b40ea68994e9fc65e76d21866a1dadb to your computer and use it in GitHub Desktop.
Save moyerr/1b40ea68994e9fc65e76d21866a1dadb to your computer and use it in GitHub Desktop.
A modifier that provides automatic sizing for sheets in SwiftUI (iOS 16+)
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