Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Complex view setup in UIVIew or UIViewController? (Design decision)

At the moment I setup most of my UI programmatically. There are two ways of arranging the views that belong to a screen (additionally to using nibs):

  • In the view controller, manage all the views (it's a view controller!)
  • Make a custom UIView subclass, and just wire that one up in the controller

I know both will work, but in which situations would you chose which solution?

Also, for the first variant, one has the option to do the setup in viewDidLoad and add the views to self.view, or build a container view and add all the views in loadView. Any good advice here would also be appreciated.

The second variant comes close to using a nib, when you would set a complete view as a controller's view.

Not intended to start a religious war here, but looking for arguments for both approaches.

like image 676
Eiko Avatar asked Jan 07 '11 19:01

Eiko


2 Answers

I can think of a couple of criteria which I would use to choose one option or the other.

If the set of views is, or could be, a reusable component shown on many screens I would favor creating a UIView subclass.

If the view controller needs to access a number of the views directly I would construct them in the controller. I try to make custom UIView classes opaque containers so their controller only needs to interact with the parent view, not dig around through its child views.

If the set of views cannot present an API dealing with a single concept, for example if the view hierarchy exists only to set the z-index of the views correctly and those views deal with displaying unrelated data, then I would again create them in the controller. A UIView subclass should be responsible for displaying only a single coherent set of data, or managing a set of sub views in a consistent way.

If views need to be positioned relative to views outside their hierarchy I would again favor defining them in the controller.

like image 102
Jonah Avatar answered Sep 28 '22 04:09

Jonah


Think MVC (Modal, View, Controller) in this case.

A good choice is to create a separate UIView class and set the UIViewController's view to this (or add it as a subview to the controller's view), then use delegate methods for any user interaction from your UIView subclass to the controller.

However, if you're only planning to have one view in your controller's view (so no exchanging views, flipping, etc.) you could essentially just use the controller's view for all UI.

like image 40
runmad Avatar answered Sep 28 '22 06:09

runmad