Presenting a partially visible bottom sheet in SwiftUI on iOS 16
Published on: June 6, 2022This post is up to date for Xcode 15 and newer. It supersedes a version of this post that you can find here
On iOS 15, Apple granted developers the ability to present partially visible bottom sheets using a component called UISheetPresentationController
. Originally, we had to resort to using a UIHostingController
to bring this component to SwiftUI.
With iOS 16, we don't have to do this anymore. You can make use of the presentationDetents
view modifier to configure your sheets to be fully visible, approximately half visible, or some custom fraction of the screen's height.
To do this, you can apply the presentationDetents
modifier by applying it to your sheet's content:
struct DetentsView: View {
@State var isShowingSheet = false
var body: some View {
Button("Show the sheet!") {
isShowingSheet = true
}
.sheet(isPresented: $isShowingSheet) {
ZStack {
Color(red: 0.95, green: 0.9, blue: 1)
Text("This is my sheet. It could be a whole view, or just a text.")
}
.presentationDetents([.medium, .fraction(0.7)])
}
}
}
Here's what the sheet looks like when it's presented on an iPhone:
In this example, my sheet will initially take up about half the screen and can be expanded to 70% of the screen height. If I want to allow the user to expand my sheet to the full height of the screen I would add the .large
option to the list of presentationDetents
.
By default, sheets will only support the .large
detent so you don't need to use the presentationDetents
view modifier when you want your sheet to only support the view's full height.