I have the following code to show a popoverview (dialog) without an arrow, which works fine. The only problem is, that the dialog is shown in the top left (IPad). I would like to center the view on the screen.
What to change or add in my following code ? :
func show_help(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewControllerWithIdentifier("Help") as! UIViewController
controller.modalPresentationStyle = UIModalPresentationStyle.popover
let popoverPresentationController = controller.popoverPresentationController
// result is an optional (but should not be nil if modalPresentationStyle is popover)
if let _popoverPresentationController = popoverPresentationController {
// set the view from which to pop up
_popoverPresentationController.sourceView = self.view;
_popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.allZeros;
// present (id iPhone it is a modal automatic full screen)
self.presentViewController(controller, animated: true, completion: nil)
}
}
Additional Infos
In my view, which is linked to my viewcontroller I set the preffered size like this:
override func viewDidLoad() {
let dialogheigth:CGFloat = self.view.frame.height * 0.5;
let dialogwidth:CGFloat = self.view.frame.width * 0.5;
self.preferredContentSize = CGSizeMake(dialogwidth,dialogheigth);
}
You need to provide the source rect for the popover.
From the apple documentation: the source rect is the rectangle in the specified view in which to anchor the popover. Use this property in conjunction with the sourceView property to specify the anchor location for the popover.
In your case, under
_popoverPresentationController.sourceView = self.view;
add:
_popoverPresentationController.sourceRect = CGRectMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds),0,0)
It will do the trick!
Here's an implementation using Swift 3
let popover = storyboard?.instantiateViewController(withIdentifier: "popover") as! PopoverVC
popover.modalPresentationStyle = UIModalPresentationStyle.popover
popover.popoverPresentationController?.backgroundColor = UIColor.green
popover.popoverPresentationController?.delegate = self
popover.popoverPresentationController?.sourceView = self.view
popover.popoverPresentationController?.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
popover.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
self.present(popover, animated: true)
Based on Istvan's answer
Swift 4 implementation :
popover.popoverPresentationController?.sourceRect = CGRect(x: view.center.x, y: view.center.y, width: 0, height: 0)
popover.popoverPresentationController?.sourceView = view
popover.popoverPresentationController?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With