Skip to content

Instantly share code, notes, and snippets.

@weAreJack
Created August 15, 2024 21:46
Show Gist options
  • Save weAreJack/974da09b0ac5720aa3f3b68e3de852b1 to your computer and use it in GitHub Desktop.
Save weAreJack/974da09b0ac5720aa3f3b68e3de852b1 to your computer and use it in GitHub Desktop.
import SwiftUI
struct SelfSizingSheet: ViewModifier {
@State private var height: CGFloat = .zero
private struct InnerHeightPreferenceKey: PreferenceKey {
static let defaultValue: CGFloat = .zero
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
value = nextValue()
}
}
func body(content: Content) -> some View {
content
.overlay {
GeometryReader { geometry in
Color.clear.preference(key: InnerHeightPreferenceKey.self, value: geometry.size.height)
}
}
.onPreferenceChange(InnerHeightPreferenceKey.self) { newHeight in
height = newHeight
}
.presentationDetents([.height(height)])
}
}
public extension View {
func selfSizingSheet() -> some View {
modifier(SelfSizingSheet())
}
}
// Usage
#Preview {
Color.white
.sheet(isPresented: .constant(true)) {
VStack {
RoundedRectangle(cornerRadius: 8)
.fill(Color.red)
.frame(height: 30)
RoundedRectangle(cornerRadius: 8)
.fill(Color.green)
.frame(height: 60)
RoundedRectangle(cornerRadius: 8)
.fill(Color.blue)
.frame(height: 120)
}
.padding(16)
.selfSizingSheet()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment