How to configure UIKit bottom sheet with custom size
With iOS 16, we can ask for any size we want!
Published: June 8, 2022 Sponsored See booksiOS 15 brought great UIKit addition in the form of “bottom sheet”. For content that does not need the entire screen. However, we weren’t able to customize its size - meaning height. It would always take roughly half of the screen on iPhone and optionally expand to a full modal sheet, which was available since iOS 13.
This is no longer the case with iOS 16. Now we can ask for any height we want. The new API seamlessly fits into the previous one, and is enabled by configuring the detents
property.
In addition to system-defined .medium
and .large
we can create .custom
. Custom detent takes a closure whose job is to return the desired height.
Bottom sheet with custom height
Here is the most basic example:
if let sheet = viewController.sheetPresentationController {
sheet.detents = [
.custom { _ in
return 200
}
]
}
And we will get a bottom sheet that is 200 points tall. It automatically deals with safe area insets where needed.
Relative height
Want a bottom sheet that is 30% or 60% of the available height? This is easily done thanks to the context
we get passed in. It has maximumDetentValue
, which specifies the maximum height possible for the sheet.
Multiply it by 0.6 to get 60% of the height.
if let sheet = viewController.sheetPresentationController {
sheet.detents = [
.custom { _ in
return 200
},
.custom { context in
return context.maximumDetentValue * 0.6
}
]
}
Of course, you can have more complex calculations to fit your needs.
You can also extend UISheetPresentationControllerDetentIdentifier
with static
identifier for your custom sizes; this way, you can refer to them when configuring other options for the sheet presentation controller, like controlling the dimming effect with largestUndimmedDetentIdentifier
.
See WWDC 22 “What’s new in UIKit” for details about these new features.
More bottom sheet options
For more about the bottom sheets in UIKit, check out my previous post, which shows how to use the system sizes, configuration options, animations, and more.