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);
}
Basically consist of three steps (iOS 8):
Let's say, you want to show a custom view to ask for a Review to the user.. here the function
loadNibForRate()
returns an instance ofRateDialog
loaded from its nib, but you can use here any way you desire to locate yourUIViewController
In iOS8, you don't need to use
self.view.frame
to calculate width and height.You can the dialog height and width using the following way:
Edited:
You can also set
contentSizeForViewInPopover
as below too:Let me know this helps or not?
Swift 4.1
Here is the simple solution:
Take a public variable
var popover
Present
YourViewController
as popover, use thepopover?.sourceRect
as mentioned below.use
viewWillTransition
for view transitions landscape and portrait.this will give you popover center aligned to screen in both landscape and portrait. Much flexible while using split view for iPad.
Swift 4 implementation :
Another way for Swift 3 (Xcode 8, iOS 9) is this:
Called from somewhere:
Function that gets called before segue gets fired:
Remember to set the storyboard segue's Kind attribute to "Present as Popover" and Anchor attribute to any view in your previous view controller.