0
votes

I have a view controller A, which has a xib in the storyboard. Then I subclass B from A.

Right now I want to present a view controller of B.

If I do something like

self.presentViewaController(B.init(), animated: true)

It's actually working, but not loading the xib. The app will crash saying the collectionView is nil. Let's say the xib has a collectionView, and in class A:

class A: UIViewController {
    @IBOutlet weak var collectionView: UICollectionView!
}

class B: A {
    //Should be empty right? since it inherits from A,
   // but the collectionView from super class is not initialized.
}

How do I fix this issue so that when I instantiate B, I can have the collectionView initialized?

1

1 Answers

1
votes

You should instantiate and keep a reference to the ViewController like so:

var viewController = someViewController(nibName: "SomeViewController", bundle: nil)

Then present like so:

self.presentViewController(viewController, animated: true)

You can of course simply present like this, but it's disgusting.

self.presentViewController(someViewController(nibName: "SomeViewController", bundle: nil), animated: true)

You may or may not need to keep track of your ViewControllers but it will lead to flexibility down the line.

Additionally, you should check out the delegate pattern paradigm, it's important that the same ViewController which presents a child ViewController, dismisses the child also. Rather than the alternative, where the child 'self destructs'.