iOS Swift subclassing ViewController initialized by xib (nib) file

走远了吗. 提交于 2021-01-27 06:08:26

问题


I have one base class

MyViewController: UIViewController

initialized by MyViewController.xib with some outlets. I only have set File Owner class in MyViewController.xib to MyViewController, no any init methods in MyViewController.swift (all inherited from UIViewController), and following line works just as expected:

let vc = MyViewController()

view property is set, outlets is set.

I wish to subclass MyViewController:

SecondViewController: MyViewController
{
    override init()
    {
        super.init()
    }

    required init?(coder aDecoder: NSCoder)
    {
        super.init(coder: aDecoder)
    }
}

Now I expect that line

let vc = SecondViewController()

will create view controller with view and outlets inherited from MyViewController, but all outlets in vc are nil. Looks like MyViewController.xib file is now missed. What am I doing wrong?


回答1:


You can't extend the xib file. The SecondViewControllershould have its own xib file and its own outlets. You may define the common UI components in the base class MyViewController and for each xib you create, link the ui components directly to the base class. For example, if you have a common custom back button in all view controller, add the outlet definition in the base class and for each xib file add the UIButton and set its outlet to the base class.



来源:https://stackoverflow.com/questions/36419948/ios-swift-subclassing-viewcontroller-initialized-by-xib-nib-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!