Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - is it possible to inherit view controller with xib file? and how?

I have a few view controllers which would have same background image and one or two buttons. Rest of the content would be different for each controller. I would like to create BaseViewController which would have .xib file and in which I would set background image, buttons and other stuff with constraints. Then I would like create subcontrollers (HomeViewController, GameViewController and so) which just inherit from BaseViewController and have all stuff set in Interface Builder. Is it possible? And subcontrollers would have set own stuff in Storyboard? Background image set in .xib for superclass and tableView in Storyboard for subclass. I know it would be possible when I would set all stuff in code but is it possible with .xib and IB?

I was thinking about usage of Container view but it's possible that I would like to change BaseViewController and maybe create more supercontrollers so I think if it is possible it would be easier with inheritance.

Edit:

Possible way suggested by iphonic. It's based on two controllers that together enabled other controllers to be subclass. BaseGameDesignViewController has .xib file and no more code in controller other than default. Code below is from BaseGameViewController from which inherits other controllers. This has problem with unwind segue which when rolling down has white screen.

override func viewDidLoad() {
    super.viewDidLoad()

    var viewController = BaseGameDesignViewController(nibName: "BaseGameDesignViewController", bundle: nil) as BaseGameDesignViewController
    contentView = viewController.view
    viewController.homeButton.addTarget(self, action: "homeButtonTapped:", forControlEvents: .TouchUpInside)
    self.view.insertSubview(contentView, atIndex: 0)
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()

    contentView.frame = self.view.frame
}


func homeButtonTapped(sender: AnyObject) {
    self.performSegueWithIdentifier("backToMainSegue", sender: self)
}
like image 268
Libor Zapletal Avatar asked May 07 '15 09:05

Libor Zapletal


1 Answers

This is impossible.

The best solution you can achieve is either based on:

  1. Container views

    • having a dedicated view XIB which is then included into every controller
  2. Outlets defined in superclass but copy-pasting everything in Interface Builder.

    • you can avoid code duplication but you won't avoid duplication in IB.
like image 178
Sulthan Avatar answered Oct 23 '22 03:10

Sulthan