Search code examples
iosswiftswift3uinavigationcontrolleruiblureffect

UINavigationController - clear background using UIBlurEffect


I am using UIBlurEffect in a UIViewController which is presented with a .crossDissolve transition style. The UIViewController has a collectionView added to its view so both have a clear background.

HomeViewController.swift

func showLiveDealsCategory(sender:UITextField){
    let catSelection = LiveDealCategorySelection()
    //let navContr = UINavigationController(rootViewController: catSelection)
    catSelection.modalPresentationStyle = .custom
    catSelection.modalTransitionStyle = .crossDissolve
    self.present(catSelection, animated: true, completion: nil)
}

LiveDealCategorySelection.swift

func setupBackgroundView(){
    if !UIAccessibilityIsReduceTransparencyEnabled() {
        self.view.backgroundColor = .clear
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = (self.view?.bounds)!
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        self.view?.addSubview(blurEffectView)
    } else {
        self.collectionView?.backgroundColor = UIColor.black
    }
}

This is the result where you can see the mapView behind LiveDealCategorySelection:

enter image description here

The problem is when I embed the view controller inside a UINavigationController because I am not able to set its background color to .clear:

func showLiveDealsCategory(sender:UITextField){
        let catSelection = LiveDealCategorySelection()
        let navContr = UINavigationController(rootViewController: catSelection)
        catSelection.modalPresentationStyle = .custom
        catSelection.modalTransitionStyle = .crossDissolve
        self.present(navContr, animated: true, completion: nil)
}

In LiveDealCategorySelection I tried:

 override func viewWillAppear(_ animated: Bool) {
        if self.navigationController != nil {
            self.navigationController!.view.backgroundColor = .clear
            self.navigationController!.view.tintColor = .clear
        }
  }

and I also tried to set the background color to .clear when I instantiate the navigation controller but I get a black background. Any idea?


Solution

  • You just forgot to move the presentation style to the UINavigationController

    navContr.modalPresentationStyle = .custom