0
votes

I'm creating a popover using popoverPresentationController in Swift. It displays fine for the first time but when I rotate the device it changes its source position.
How can I make it stick at its original source point irrespective of the orientation?

The code that i did.

@IBAction func btn_popover_click(sender: UIButton) {

    let menuViewController = PopoverViewController()
    menuViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
    menuViewController.preferredContentSize = CGSizeMake(50, 100) // Size of popover.

    popoverMenuViewController = menuViewController.popoverPresentationController
    popoverMenuViewController?.permittedArrowDirections = .Any
    popoverMenuViewController?.delegate = self
    popoverMenuViewController?.sourceView = sender.superview
    popoverMenuViewController?.sourceRect = sender.frame
    presentViewController(
        menuViewController,
        animated: true,
        completion: nil)
}
2

2 Answers

2
votes

Swift 3

Make sure the view controller presenting the popover conforms to UIPopoverPresentationControllerDelegate.

Example:

class MyViewContoller: UIVIewContoller, UIPUIPopoverPresentationControllerDelegate 
{

// your code...

// MARK: UIPopoverPresentationControllerDelegate Methods

func popoverPresentationController(_ popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverTo rect: UnsafeMutablePointer<CGRect>, in view: AutoreleasingUnsafeMutablePointer<UIView>) {
    let viewFrame = popoverPresentationController.presentingViewController.view.frame
    let deltaX = viewFrame.height - rect.pointee.midX
    rect.pointee = CGRect(x: viewFrame.width - deltaX, y: rect.pointee.maxY, width: 0, height: 0)
}
-1
votes

I think you should consider about AutoLayout, which is efficient way handle the object's(like Label, Button,etc) position and size on the different size screens and rotation screens. AutoLayout can be set in the storyboard or as the part of your code.

By the way, the AutoLayout is so much that it is hard to say. I recommend you see this Tutorial about the AutoLayout.