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 li
Swift 4 implementation for center Popover controller
let navigationController = UINavigationController(rootViewController: controller)
navigationController.modalPresentationStyle = .popover
navigationController.modalPresentationStyle = UIModalPresentationStyle.popover
let popover = navigationController.popoverPresentationController
controller.preferredContentSize = CGSize(width:500,height:600) //manage according to Device like iPad/iPhone
popover?.delegate = self
popover?.sourceView = self.view
popover?.sourceRect = CGRect(x: view.center.x, y: view. .y, width: 0, height: 0)
popover?.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
self.present(navigationController, animated: true, completion: nil)
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)
Add the below mentioned line of code to make it centre.
popoverController.popoverPresentationController?.sourceView = view
popoverController.popoverPresentationController?.sourceRect = view.bounds
In case if it helps anyone, I have created an extension on UIViewController
extension UIViewController{
func configureAsPopoverAndPosition(withWidthRatio widthRatio:CGFloat,
heightRatio:CGFloat){
modalPresentationStyle = .popover
let screenWidth = UIScreen.main.bounds.width
let screenHeight = UIScreen.main.bounds.height
let popover = popoverPresentationController
popover?.sourceView = self.view
popover?.permittedArrowDirections = [UIPopoverArrowDirection(rawValue: 0)]
preferredContentSize = CGSize(width: (screenWidth * widthRatio),
height: (screenHeight * heightRatio))
popover?.sourceRect = CGRect(x: view.center.x,
y: view.center.y,
width: 0,
height: 0)
}
}
Usage:
if UIDevice.current.userInterfaceIdiom == .pad{
yourViewController.configureAsPopoverAndPosition(withWidthRatio: 0.7 /*Make view controller width 70 % of screen width*/,
heightRatio: 0.7/*Make view controller height 70 % of screen height*/)
}
This will show the popover at center of the screen.