I am using UISheetPresentationController to present a sheet. Everything works fine except I am not able to modify width of the sheet in landscape mode. As per design the width has to be 60% of the view bounds. In Apple talk: https://developer.apple.com/videos/play/wwdc2021/10063/ It is mentioned that we can resize sheet to preferredContentSize if this flag is set to true:
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = true
But this does not work. Here is my code:
class BottomSheetController<Content: View>: UIViewController {
private var hostingController: UIHostingController<Content>?
init( content: @escaping () -> Content) {
self.hostingController = UIHostingController(rootView: content())
super.init(nibName: nil, bundle: nil)
configureSheetProperties()
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
guard let hostingController = hostingController else { return }
addChild(hostingController)
view.addSubview(hostingController.view)
hostingController.didMove(toParent: self)
hostingController.view.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
hostingController.view.topAnchor.constraint(equalTo: view.topAnchor),
hostingController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
hostingController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor),
hostingController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
}
private func configureSheetProperties() {
modalPresentationStyle = .pageSheet
preferredContentSize = CGSize(width: view.bounds.width * 0.6, height: view.bounds.height)
if let sheet = sheetPresentationController {
sheet.prefersGrabberVisible = true
sheet.prefersScrollingExpandsWhenScrolledToEdge = false
sheet.prefersEdgeAttachedInCompactHeight = true
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = true
sheet.preferredCornerRadius = 20
sheet.detents = [.medium()]
}
}
open override var preferredContentSize: CGSize {
get {
return CGSize(width: view.bounds.width * 0.6, height: super.preferredContentSize.height)
}
set {
super.preferredContentSize = CGSize(width: view.bounds.width * 0.6, height: newValue.height)
}
}
}
preferredContentSize
isn't respected when using the pageSheet
style.
If you set modalPresentationStyle = .formSheet
, it should work.
Also, in your override of preferredContentSize
, view.bounds.width
is the width of self in the sheet, which means you're defining the width recursively to be 60% of itself, which will probably loop and collapse to 0. Something like view.window.bounds.width * 0.6
should work better, to be 60% of the window width.