Search code examples
iosswiftuitableviewswift2uipopovercontroller

Modify width of Popover View Controller


I am trying modify the width of my popover, which is a UITableViewController, so that it only takes up half of the width of the parent view. The popover is called programmatically when a button in another UITableView (the parent view) is tapped. I tried setting the preferredContentSize of the popover and setting the sourceRect but the popover still takes over the entire screen.

class MyTableViewController: UITableViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIDynamicAnimatorDelegate, UIGestureRecognizerDelegate, CLLocationManagerDelegate, UIPopoverPresentationControllerDelegate, UIAdaptivePresentationControllerDelegate {

...

func goToPlaces(button: UIButton) {

        let fromRect = CGRectMake(50.0, 50.0, self.view.bounds.width / 2.0, self.view.bounds.height)
        let popoverVC = storyboard?.instantiateViewControllerWithIdentifier("otherPlaces")
        popoverVC?.modalPresentationStyle = .OverFullScreen
        presentViewController(popoverVC!, animated: true, completion: nil)
        popoverVC?.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.6)
        popoverVC?.preferredContentSize = CGSizeMake(self.view.bounds.width / 2.0, self.view.bounds.height)
        let popoverController = popoverVC?.popoverPresentationController
        popoverPresentationController?.sourceView = self.view
        popoverPresentationController?.sourceRect = fromRect
        popoverController?.permittedArrowDirections = .Any
        popoverController?.delegate = self


    }

func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
        return .None

    }

EDIT: When I do a print of popoverPresentationController?.sourceView and popoverPresentationController?.sourceRect

they both return nil for some reason


Solution

  • You are asking for

    popoverVC?.modalPresentationStyle = .OverFullScreen
    

    so you get it covering the whole screen. Try using:

    popoverVC?.modalPresentationStyle = .Popover
    

    The

    presentViewController(popoverVC!, animated: true, completion: nil)
    

    should also be last so that the delegate can get the calls for which it wants to respond. (I think -- it might not matter if UIKit is actually delaying the presentation.)