Search code examples
iosswiftpopover

swift - Popover pointer is not pointing towards its caller


I'm making a pretty regular popover but wherever I place it, it points slightly above the caller button.

I connected the popover through the storyboard. Inside the popoverviewcontroller I placed a view which contains the buttons. The code for the viewdidload() of the popoverviewcontroller is:

override func viewDidLoad() {
    super.viewDidLoad()

    self.preferredContentSize = popoverView.frame.size
        }

Is it happening because I placed the button too close to the top?

enter image description here


Solution

  • You need to provide anchor point for the popover by using sourceView and sourceRect properties. Make use of the prepareForSegue func of the presenting controller to set properties of the popover like below:

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "SegueIdentifier" {
            let destController = segue.destinationViewController
            let popover = destController.popoverPresentationController;
    
            destController.popoverPresentationController!.delegate = self
            destController.preferredContentSize = CGSize(width: 320, height: 186)
            popover?.sourceView = self.button;
            popover?.sourceRect = self.button.bounds
        }
    }
    

    You can also provide preferredContentSize here as this way the code is more modular and your content view controller can be used elsewhere too.

    In my understanding, linking the pop over segue in storyBoard means you have provide sourceView. As per Apple docs, to provide anchor point use sourceView in conjunction with sourceRect. I am guessing if you do not provide sourceRect (as in your case using storyboards), OS takes the origin of the view which is why the arrow of popover is not proper. Specifying suitable sourceRect will improve your result.