Skip to content

Instantly share code, notes, and snippets.

@DisappearPing
Forked from susanstevens/iphone-popover.md
Created April 11, 2022 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DisappearPing/07dfc0e4c981a58862158fad94d22e5c to your computer and use it in GitHub Desktop.
Save DisappearPing/07dfc0e4c981a58862158fad94d22e5c to your computer and use it in GitHub Desktop.
How to Create a Popover on iPhone

How to Create a Popover on iPhone

Storyboard set up

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.

storyboard

When adding the segue between view controllers, select "Present as Popover".

segue

Code

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
    }
}
  1. Access the popover's popoverPresentationController. This is the object that manages the presentation of the popover.
  2. Set your view controller as the popover presentation controller's delegate.
  3. 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.

popover

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment