Reputation: 4330
I want to use some different templates (say like 5, and can grow after) for every viewController in my App.
There are some different approaches I can think of:
Having the same storyboard and creating 5 xibs for each scene in the storyboard, so ill set the file owner to the current vc in the storyboard, and i add a subview like:
view.addSubview(NSBundle.mainBundle().loadNibNamed(“Template1_First_Screen”, owner: self, options: nil).first! as UIView)
The down here maybe is that they are less maintained by apple and can be outdated? This seems at least the more neat since i’m only adding a view to the current vc
Upvotes: 0
Views: 75
Reputation: 52227
Instead of creating several templates for fat ViewControllers, you should try to factor out everything that is not directly dealing with views.
So it shouldn't implement data sources and I usually only implement intermediate delegates i.e. for table views in the way that another class gets a call back block to populate cells.
if you do this you can get even to an state, where you don't need custom view controllers at all. See http://www.objc.io/issue-1/lighter-view-controllers.html, http://chris.eidhof.nl/posts/intentions.html and https://bendyworks.com/single-responsibility-principle-ios/
I wrote a small example to illustrate my idea: https://github.com/vikingosegundo/ViewControllerThemer
it themes a given view, in this case only background color. but could be anything
the intentions that does the theming uses an enum to select the right theme in a switch statement. It is passed in as a user defined runtime attribute in the storyboard. In real world I probably would create another intention that implements a datasource of the theme intentions and provides it with the needed values.
note that I use plain UIViewController in this example. Unreal world application I would acetate a base controller aka ThemeableViewController which defines all the able elements.
Upvotes: 0
Reputation: 2856
I would suggest option 4: create different xibs and don't involve storyboards at all. I believe this will lead to simpler application architecture in general and add more flexibility.
This seems odd to keep storyboards only for navigation (if it is the only storyboard's responsibility).
update
Considering proposed way of intialising view
property option 3 doesn't seems to be odd.
class ViewController: UIViewController {
override func loadView() {
view = NSBundle.mainBundle().loadNibNamed("View", owner: self, options: nil).first! as UIView
}
}
The initial comment regarding oddness of the approach was written with this option in mind:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(NSBundle.mainBundle().loadNibNamed("View", owner: self, options: nil).first! as UIView)
}
}
Upvotes: 2