使自定义viewcontroller覆盖导航栏

时间:2018-02-28 15:19:52

标签: ios swift view uinavigationbar viewcontroller

我在主视图控制器上显示自定义弹出窗口。为此,我在故事板中创建了一个viewcontroller(显示的图像),相应的类如下所示。

enter image description here

class PopUpViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        self.showAnimate()
    }

    func showAnimate()
    {
        self.view.alpha = 1.0
    }

    func removeAnimate()
    {
        UIView.animate(withDuration: 0.0, animations: {
            self.view.alpha = 0.0;
        }, completion:{(finished : Bool)  in
            if (finished) {
                self.view.removeFromSuperview()
            }
        });
    }
}

然后在我的主视图控制器中,我按下按钮点击弹出,如下所示:

let popOverVC = UIStoryboard(name: "MainViewController", bundle: nil).instantiateViewController(withIdentifier: "popup") as! PopUpViewController
self.addChildViewController(popOverVC)
popOverVC.view.frame = self.view.bounds
self.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: self)

当添加弹出窗口时,这会使主视图控制器的背景变为黑色,不透明度为70%。如何使导航栏也具有相同的背景效果?

我尝试过更新:

self.view.window?.backgroundColor = UIColor.black.withAlphaComponent(0.7)

self.navigationController?.navigationBar.backgroundColor = UIColor.black.withAlphaComponent(0.7)
在viewDidLoad()中

但是没有用。任何可能的解决方案?

1 个答案:

答案 0 :(得分:4)

如果我理解正确,您将popOverVC作为子视图添加到mainViewController中嵌入UINavitationController的视图中。如果是这种情况,那么popOverVC不会覆盖navigationBar是合乎逻辑的,因为navigationBar是navigationController的子视图,而不是mainViewController的子视图。为了能够覆盖navigationBar,您必须将popOverVC添加到navigationController

// to make things a bit easier working with the optional self.navigationController
guard let navController = self.navigationController else { return }

let popOverVC = UIStoryboard(name: "MainViewController", bundle: nil).instantiateViewController(withIdentifier: "popup") as! PopUpViewController
navController.addChildViewController(popOverVC)
popOverVC.view.frame = navController.view.bounds
navController.view.addSubview(popOverVC.view)
popOverVC.didMove(toParentViewController: navController)