Skip to content

Instantly share code, notes, and snippets.

@susanstevens
Last active September 8, 2023 02:25
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save susanstevens/4ecff3b4b0aa2856efe6d2d54619d407 to your computer and use it in GitHub Desktop.
Save susanstevens/4ecff3b4b0aa2856efe6d2d54619d407 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

@ravanar-sk
Copy link

This is really good.

@DisappearPing
Copy link

Work perfectly.

@NikAlex09
Copy link

Does not work on iPhone.

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