Hey! 👋
Let’s explore how to customize sheet sizes in SwiftUI using the Presentation Detents feature.
We have four main approaches to achieve this:
Predefined Detents: SwiftUI offers predefined detents, such as .medium and .large, which provide a convenient way to set specific sheet sizes.
Fractions: Another approach is to specify a fraction of the available height using a value between 0 and 1.0. This allows you to customize the sheet size to a specific percentage of the screen.
Fixed Height: If you prefer a fixed sheet size, you can use the fixed height option. This method ensures that the sheet remains the same size regardless of the screen size.
Custom: For more advanced customization, you can create your own type that conforms to the CustomPresentationDetent protocol. This allows you to override the height(in:) method to set your desired sheet size.
In today’s example, I’ll demonstrate the first three approaches.
Tip: You can define multiple detents. The default value will be the first one you specify. By providing more than one value, you enable the user to resize the sheet.
🚨 Full code below and also on Github
🤝 Find more about me on saidmarouf.com. I’m also on X, Threads, and LinkedIn
import SwiftUI
struct SheetsExampleView: View {
@State var isPresented: Bool = false
var body: some View {
VStack {
Button {
isPresented.toggle()
} label: {
Text("Show Sheet").font(.largeTitle)
}.buttonStyle(.borderedProminent)
}
.sheet(isPresented: $isPresented) {
MySheetView()
}
}
}
struct MySheetView: View {
var body: some View {
VStack {
Text("Hello! I am a sheet")
.frame(maxWidth: .infinity, maxHeight: .infinity)
.font(.largeTitle)
.background(.purple)
}
.presentationDetents([.medium, .large])
//.presentationDetents([.fraction(0.5), .large])
//.presentationDetents([.fraction(0.3), .fraction(0.7)])
//.presentationDetents([.height(200)])
}
}
#Preview {
SheetsExampleView()
}
SwiftUI FYI #14 - Sheet Presentation Detents