我创建了第二个窗口,在其中添加了一个navVC,然后nav的根是blueVC。
在blueVC中,我有一些逻辑,要么显示一个webView(我隐藏了navBar),要么在必要时添加另一个vc(redVC-show navBar)作为一个孩子。
问题是在redVC中我添加了一个barbuttonem,但它没有出现。navVC是存在的,但我似乎也无法访问navBar的任何属性。
我哪里有问题?

let secondWindow = SecondWindow() // subClassed from UIWindow

var navVC: UINavigationController?
let blueVC = BlueVC()

func launchSecondWindow() {

    navVC = UINavigationController(rootViewController: blueVC)

    secondWindow.frame = CGRect ...
    secondWindow.rootViewController = navVC!
    secondWindow.backgroundColor = .clear
    secondWindow.windowLevel = UIWindow.Level.normal
    secondWindow.rootViewController = safeNavVC
    secondWindow.makeKeyAndVisible()

    // doesn't show, the navBar stays gray
    secondWindow.rootViewController?.navigationController?.navigationBar.barTintColor = .purple

    // present it
}

蓝VC:
BlueVC: UIViewController {

let redVC = RedVC()

logic() {

    // some logic that decides to add the webView or the redVC

    if !redVC.view.isDescendant(of: self.view) {

        addChild(redVC)
        redVC.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(redVC.view)
        redVC.didMove(toParent: self)

        redVC.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        redVC.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        redVC.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        redVC.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }
}

红色VC:
RedVC: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // doesn't show
    navigationItem.title = "123"

    // doesn't show
    navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(...))
}
}

最佳答案

问题是我把导航标题和barbuttonem添加到了错误的vc中。既然redVC是blueVC的孩子,blueVC就是我应该添加它的地方。

BlueVC: UIViewController {

let redVC = RedVC()

logic() {

    // some logic that decides to add the webView or the redVC

    if !redVC.view.isDescendant(of: self.view) {

        // ** now it shows shows
        navigationItem.title = "123"

        // ** now it shows
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(...))

        addChild(redVC)
        redVC.view.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(redVC.view)
        redVC.didMove(toParent: self)

        redVC.view.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        redVC.view.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        redVC.view.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        redVC.view.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }
}

10-08 07:43