0

I've defined a base class with an outlet and attached the outlet to the view in the nib file

class BaseController: UIViewController  {


@IBOutlet weak var myView : UIView!

and then created a subclass 

class SubViewController: BaseController {

override func viewDidLoad() {
myView.backgroundColor = UIColor.red //The app crashes here 

When i call BaseController() it view appears, but when I call SubViewController() the app crashes because myView is nil. The files owner on the nib file is BaseController.

J.Doe
  • 697
  • 2
  • 16
  • 26
  • 2
    Use `SubViewController.init(nibName: String?, bundle: Bundle?)` – Evgeniy Gushchin Aug 15 '17 at 09:41
  • I don't understand what do you mean. Is it possible to use a nib file that contain a UIView with different viewController, to allow each controller fraw something different in the view? – J.Doe Aug 15 '17 at 09:55
  • How did you `init` your `SubViewController`? The thing is since the super class have a `IBOutlet` linked in a Xib, you have to the parent with the xib to be able to use the IBOulet. Same for the children. – Larme Aug 15 '17 at 10:13
  • @J.Doe You should init your view controller with nib file. So you should use method that was mentioned above. `SubViewController.init(nibName: "Here should be name of your nib file", bundle: nil)` – Evgeniy Gushchin Aug 15 '17 at 12:10

1 Answers1

5

Try to create custom initializer in your subclass:

init() {
    super.init(nibName: "BaseController", bundle: nil)
}
krlbsk
  • 1,051
  • 1
  • 13
  • 24
  • Can this same approach be done with a UIView rather than a ViewController? – Chucky Feb 26 '21 at 15:31
  • @Chucky No. Loading `UIView` from xib is done a little bit different. Check this https://stackoverflow.com/a/35666644/4646572. – krlbsk Feb 26 '21 at 15:35
  • Thanks! And can I share the outlets of the base class this way? ie Baseview : UIView, Subview : BaseView – Chucky Feb 26 '21 at 16:00