UINavigationController - 使用 UIBlurEffect 清除背景

UINavigationController - clear background using UIBlurEffect

我在 UIViewController 中使用 UIBlurEffect,它以 .crossDissolve 过渡样式呈现。 UIViewController 在其视图中添加了一个 collectionView,因此两者都有清晰的背景。

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
    }
}

这是你可以看到后面的 mapView 的结果 LiveDealCategorySelection:

问题是当我将视图控制器嵌入 UINavigationController 时,因为我无法将其背景颜色设置为 .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)
}

LiveDealCategorySelection 我试过:

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

并且我还尝试在实例化导航控制器时将背景颜色设置为 .clear,但我得到的是黑色背景。有什么想法吗?

使用导航控制器无法实现您想要的。只有带有 OverCurrentContext 的模态呈现,支持从一个视图控制器转换到另一个具有透明或半透明背景的视图控制器。

如果你想模糊这个视图控制器的背景,那么使用模态呈现和 'custom (or over current context)'

呈现这个视图控制器

否则试试这个:

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

您只是忘记将呈现样式移动到 UINavigationController

navContr.modalPresentationStyle = .custom