Using a Popover presentation on an iPhone Device

Say you want to show a little popover menu on your view controller when a user presses a button. On iPad, this is pretty easy using a popover presentation, but this same thing isn’t available on iPhone devices. Trying to do that just using a container view controller or a custom view overlaid in our view controller is a huge pain and is a little messy… but, there is a solution!

1- create the view controller for your pop up inside your story board.

2- in your storyboard, set the view controllers simulated size to freeform and set its content size to use a preferred explicit size and set that size to however big you want the popup to be on screen.

3- Create a segue from the parent view controller to the menu view controller. Select Present as Popover uner Kind, set the desired appearance direction and attach an anchor to the object that you want to show it. Set the identifier to something like ‘PopoverSegue’

4- In your parent view controller prepare for the segue:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "popoverSegue" { let popoverViewController = segue.destination popoverViewController.popoverPresentationController?.delegate = self popoverViewController.popoverPresentationController?.backgroundColor = popoverViewController.view.backgroundColor if let sender = sender as? UIView { popoverViewController.popoverPresentationController?.sourceView = sender popoverViewController.popoverPresentationController?.sourceRect = CGRect(x: sender.bounds.origin.x + 21, y: sender.bounds.origin.y + 50, width: 2, height: 2) } } }   //to force the popover presentation func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // Force popover style return .none }  


Tada! That wasn’t too hard, was it?



This site uses Akismet to reduce spam. Learn how your comment data is processed.