iosswiftuiviewcontrollerbluruiblureffect

UIViewController blur background turns into gray


I would like to use blur background for my view controller but as soon as the view is loaded, the whole thing turns into gray.

I present the view controller by performing a segue from another view, and in the viewDidLoad() method of the view controller, I implement the blur effect as given below

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = UIColor.clear

    let blurBgView = UIVisualEffectView(effect: UIBlurEffect(style: .extraLight))
    blurBgView.translatesAutoresizingMaskIntoConstraints = false

    view.insertSubview(blurBgView, at: 0)

    NSLayoutConstraint.activate([
        blurBgView.heightAnchor.constraint(equalTo: view.heightAnchor),
        blurBgView.widthAnchor.constraint(equalTo: view.widthAnchor),
        ])
}

This is how it looks like

enter image description here

How can I implement a blur background for my view controller?

I use XCode 9.3, Swift 4.1

Thanks


Solution

  • Present your view controller and set its modalPresentationStyle from your initial vc:

    let newController = NewViewController()
    newController.modalPresentationStyle = .overCurrentContext
    present(newController, animated: true, completion: nil)
    

    Or, if you are preparing for the segue:

    let newController: NewViewController = segue.destination as! NewViewController
    newController.modalPresentationStyle = .overCurrentContext
    

    And in the NewViewController class in viewDidLoad() add your code.