Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS Swift subclassing ViewController initialized by xib (nib) file

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?

like image 853
Shadow Of Avatar asked Apr 05 '16 07:04

Shadow Of


People also ask

What is XIB file in iOS?

XIBs are a newer, XML based format that is used for the UI at design time. When you compile your app, the XIB files are converted to binary NIB files for you, and those binary versions of the files are embedded into your app.

How do I load a nib in Swift?

loadNibNamed("SomeView", owner: self, options: nil) self. addSubview(self. view); // adding the top level view to the view hierarchy } ... } Note that this way I get a class that loads itself from nib.

What is difference between XIB and NIB?

NIBs and XIBs are effectively the same thing: XIBs are newer and are used while you're developing, whereas NIBs are what get produced when you create a build. In modern versions of iOS and macOS, NIBs and XIBs have effectively been replaced by storyboards, although you may still meet them if you work on older projects.


1 Answers

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.

like image 57
Hossam Ghareeb Avatar answered Nov 08 '22 08:11

Hossam Ghareeb