• Display a popover in Swift

    27 March 2016

    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 :





    let storyboard:UIStoryboard=UIStoryboard(

    name:"Main",

    bundle:nil)

    varmenuViewController:MenuViewController=storyboard.instantiateViewControllerWithIdentifier("MenuViewController")asMenuViewController

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


    letmenuViewController=MenuViewController()

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



    menuViewController.modalPresentationStyle=.Popover

    menuViewController.preferredContentSize=CGSizeMake(50,100)

    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 :









    let popoverMenuViewController=menuViewController.popoverPresentationController

    popoverMenuViewController?.permittedArrowDirections=.Any

    popoverMenuViewController?.delegate=self

    popoverMenuViewController?.sourceView=sender

    popoverMenuViewController?.sourceRect=CGRect(

    x:location.x,

    y:location.y,

    width:1,

    height:1)

    presentViewController(

    menuViewController,

    animated:true,

    completion:nil)

    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 :





    func adaptivePresentationStyleForPresentationController(

    controller:UIPresentationController!)->UIModalPresentationStyle{

    return.None

    }

    Et voila !

    popover2


Comments

Comments closed on this post.