Presenting a view controller with dim background

AppsDev picture AppsDev · Jun 6, 2016 · Viewed 26.9k times · Source

I have a view controller which view's background I need to be translucent and keep showing the view below. I've adjusted the opacity in the nib file and tried both pushing the view controller into a navigation stack and presenting it modally, but when loaded, the previous view is unloaded. How could I solve this?

Answer

Anh Pham picture Anh Pham · Jun 6, 2016

Is this what you're looking for?

View Controller A -> View Controller B (nib)

Swift < 3:

In View Controller A, add the following line of code:

let viewControllerB = ViewControllerB(nibName: "ViewControllerB", bundle: nil)
viewControllerB.modalPresentationStyle = .OverFullScreen

presentViewController(viewControllerB, animated: true, completion: nil)

And in View Controller B, set the background color of view with colorWithAlphaComponent method:

view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.7)        

Swift ≥ 3:

View Controller A:

let viewControllerB = ViewControllerB(nibName: "ViewControllerB", bundle: nil)
viewControllerB.modalPresentationStyle = .overFullScreen

present(viewControllerB, animated: true, completion: nil)

View Controller B:

view.backgroundColor = UIColor.black.withAlphaComponent(0.7)