UINavigationController(rootViewController:MyViewController())触发viewdidLoad并返回nil navigationController

时间:2019-06-18 13:42:24

标签: swift uiviewcontroller uinavigationcontroller

我试图理解使用初始化程序初始化UINavigationController背后的逻辑:

UINavigationController(rootViewController: MyViewController())

我正在修改的应用程序使用了此初始化程序,并且在我拥有的MyViewController自定义初始化程序中使用了

class MyViewController:UIViewController{

    init(){
        super.init(nibName: "MyViewController", bundle: nil)
    }

}

MyViewController生命周期方法中,viewDidLoad的{​​{1}}值以前没有nil

我所做的唯一更改是在自定义初始化程序内部。现在:

navigationController

换句话说,我不想使用xib文件。这种变化使我陷入崩溃,并且在进行一些调试之后,我意识到init(){ super.init(nibName: nil, bundle: nil) /*EDIT*/ let dummyMe = UIView() view.addSubview(dummyMe) } 方法中的navigationController值是nil,但在我的viewWillAppear方法中不是。

那怎么可能? viewDidLoad初始化程序应该调用UINavigationController吗?为什么现在viewDidLoadnavigationController

谢谢

1 个答案:

答案 0 :(得分:1)

您应该检查您的代码。示例可以正常工作,您可以将其粘贴到游乐场:

import UIKit
import PlaygroundSupport

class MyViewController:UIViewController{
    override func viewDidLoad() {
        super.viewDidLoad()
        print(#function)
        print(navigationController)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print(#function)
        print(navigationController)
    }
}

let controller = UINavigationController(rootViewController: MyViewController())

此代码将不会触发生命周期方法。添加PlaygroundPage.current.liveView = controller.view即可触发并查看:

viewDidLoad()
Optional(<UINavigationController: 0x7ffb18001200>)
viewWillAppear
Optional(<UINavigationController: 0x7ffb18001200>)

UPD:

要添加自定义视图,请覆盖loadView

override func loadView() {
    super.loadView()
    let subviewFrame = view.bounds
    let dummyMe = UIView(frame: subviewFrame)
    dummyMe.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    dummyMe.backgroundColor = .yellow
    view.addSubview(dummyMe)
}

甚至:

override func loadView() {   
    let dummyMe = UIView()
    dummyMe.backgroundColor = .yellow
    view = dummyMe
}