Display a popover in Swift

On my first project i needed a popup style presentation that would have worked on iPhone and iPad.
In swift we have the UIPopoverPresentationController to deal with that need.

popover

First you need a ViewController that will be the view of your popover. You can built it in the storyboard or in code.
If its in a storyboard you will access it in code with something like that :

If you built it in code your variable setting will look like something like that :

Then you give it the .Popover modalPresentationStyle and define its preferred size :

And now the tricky part begins, you will need to present your controller and for that configure the popoverPresentationController.
For that task you need to conform to theUIPopoverPresentationControllerDelegate protocol, and your ViewController class will look like :
class ViewController: UIViewController,
UIPopoverPresentationControllerDelegate {

then you setup your presentation controller and present it :

In that example the popover is called from a tapGesture Selector, the location variable is the location of the tap recovered from the Gesture recognizer. If you access your popover from a BarButtonItem you should look at the.presentPopoverFromBarButtonItem property.
In order to work on iPad you need to set the sourceView and the sourceRect (here the sourceView is the view from witch the tapGesture occurs, if you come from a Button the sender will be that button.)

In iOS 8 we have the opportunity to present the popover with the same behavior of an iPad (in popup and not in a modal fullscreen view controller). For that purpose you need to add that method of the protocol :

Et voila !

popover2

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s