Search code examples
iosswiftbackgroundtransparencyalpha-transparency

Transparent view background turns black


I want to make the view of a view controller semi-transparent. For that I have set the background color like this in the viewDidLoad method.

view.backgroundColor = UIColor(white: 0, alpha: 0.5)

When the view controller is presented, the background appears as I need it and then it turns black right away.

enter image description here

Why is this happening?

This is the code for showing the PopupViewController:

@IBAction func didTapShowButton(_ sender: UIButton) {
    let navController = UINavigationController(rootViewController: PopupViewController())
    present(navController, animated: true, completion: nil)
}

I uploaded a demo project here as well.


Solution

  • You may add the flag overCurrentContext (or custom), so your present might be something like:

    @IBAction func didTapShowButton(_ sender: UIButton) {
        let navController = UINavigationController(rootViewController: PopupViewController())
        navController.modalPresentationStyle = .overCurrentContext
        present(navController, animated: true, completion: nil)
    }