iOS 8 introduced a new way of creating Popovers on iPad: instead of using the trusty old (nightmarish) UIPopoverController class, we can now use the UIPopoverPresentationController. It’s available on iPads as well as iPhones.
The great news for us developers is that we no longer have to check what type of device we’re on and present our content accordingly: we simply present a Popover, and if we happen to be on an iPhone, iOS will automatically show our view controller as an action sheet instead. No other code change or if-then query is necessary.
While this approach was optional in iOS 8, the UIPopoverController is now deprecated and should no longer be used in iOS 9 (and good riddens I say). Both the creation as well as dismissal process have been streamlined, and I find it’s now actually a joy rather than a chore to play with Popovers.
Let’s see how to create a simple Popover Presentation Controller in iOS 9.
Imagine you’re presenting a view controller in your storyboard via a Popover Segue: Simply drag from a button in your Main View Controller to your Other View Controller, and under segue select “Popover”. Works like a charm: the popover is presented, and if someone clicks outside the popover it is dismissed. Marvellous!
Surely we should be able to add a button inside our popover, and create an IBAction in which we call something like “dismissPopover:animated”. But of course there isn’t – at least not if you’re presenting a UIViewController.
Things would be easier if we had created our popover in code, where we could create a UIPopoverController (which has a method that dismisses it) – but if you’ve ever tried, that’s just not possible when using Storyboards: because with Storyboards, all we can create is a UIViewController, and it just doesn’t have a popover dismissal method.
So how do we do this instead?
This content is for members only.
This notification is picked up by our Main View Controller which acts accordingly and can dismiss our popover because it holds a reference to it.
Another mystery solved 😉