Add your view controllers in storyboard. In the Size Inspector, change the simulated size of the popover view controller to "Freeform". This doesn't change the popover's size when you run the app, but it does make it easier to lay out subviews correctly.
When adding the segue between view controllers, select "Present as Popover".
In your view controller, override the prepare(for:sender:)
method so that you can access the popover view controller just before it appears on screen.
Start by setting the preferredContentSize
.
class ViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.destination.preferredContentSize = CGSize(width: 300, height: 200)
}
}
At this point, if you run your app on an iPhone simulator, you'll notice that the popover view controller still covers most of the screen. By default, popovers display as full-screen when the horizontal size class is compact.
To fix this, add the following code:
class ViewController: UIViewController {
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
segue.destination.preferredContentSize = CGSize(width: 300, height: 200)
if let presentationController = segue.destination.popoverPresentationController { // 1
presentationController.delegate = self // 2
}
}
}
extension ViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController,
traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none // 3
}
}
- Access the popover's
popoverPresentationController
. This is the object that manages the presentation of the popover. - Set your view controller as the popover presentation controller's delegate.
- Implement the
adaptivePresentationStyle
method to tell the popover presentation controller how to adapt to different size classes. In this case, you don't want the popover's presentation to change, so you return.none
.