Search code examples
swiftuiviewcontrollerswift5popover

Trying to get a popover in a certain size


I'm trying to create a popover that only intends takes up a small part of a screen. I would like to open the popover from a button in the navigation bar. I've tried searching it but I was only able to find outdated posts which didn't get me any further.

I hope somebody knows a way or can hopefully point me in a direction.

Something like this is what I am trying to achieve:

screenshot


Solution:

Create a new ViewController (with a modal, cross dissolve segue to it).

2

Make the view non-opaque and make the background color of the view clear or 'darken' the background, explained a few lines under here. After that add any view (UIView, UIStackView, UILabel, UIButton, etc) on top and you can make it however you like! Code:

Swift 5:

class PopoverViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.isOpaque = false
        self.view.backgroundColor = .clear
    }
}

For 'darkening' the background set the view's background color to black with an alpha between 0.4 and 0.6 depending on how much you'd like the background to darken. Example:

Swift 5:

class PopoverViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.isOpaque = false
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.5)
    }
}

Solution

  • One of the best way to achieve this by presenting a new view controller. Things to keep in mind in order to achieve the best user experience.

    1. The transition style of this popup view controller will be Cross Dissolve
    2. The popup view controller will have a translucent background view as shown in the above image
    3. You can have you own custom popup view in this view controller over the translucent background based on your preferred size, style etc