Search code examples
iosswiftpopover

swift - Popover is not displayed correctly in landscape mode


Popover takes the complete screen when displayed in landscape mode, it works correctly in portrait mode though. Also, it is does not disappear when i click outside the popover in landscape mode.

I connected the popover through the storyboard. Inside the popoverviewcontroller I placed a view which contains the buttons. The code for the viewdidload() of the popoverviewcontroller is:

override func viewDidLoad() {
    super.viewDidLoad()

    self.preferredContentSize = popoverView.frame.size
        }

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

Portrait:

enter image description here

landscape:

enter image description here


Solution

  • You have to add UIPopoverPresentationControllerDelegateto your class like this:

    swift 3

    import UIKit
    
    class ViewController: UIViewController, UIPopoverPresentationControllerDelegate {
        ...
    

    As a second step, add the following function:

    func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
        return UIModalPresentationStyle.none
    }
    

    Explanation: By returning UIModalPresentationStyle as none, the original presentation style is kept and your popover is not streched to the bottom of your screen in landscape orientation.