Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to subclass UIViewController for custom subview?

I've seen custom subviews implemented as an UIViewController subclass, but that maybe could have been implemented as an UIView subclass.

When should I subclass UIViewController instead of UIView for a subview? Are there any drawbacks to subclassing UIViewController?

like image 419
hpique Avatar asked Mar 27 '11 14:03

hpique


2 Answers

Personally, when I need some significant logic to go on, I do it with a UIViewController subclass. Also, if I am looking for some of the behavior that you get from UIViewController e.g. presenting it modally or in a navigation controller.

If you are doing something fairly simple or lightweight, a UIView subclass is usually enough. I seem to have used them most often when making custom buttons and table view cells.

In my experience I have found myself using more UIViewController subclasses than UIView subclasses, but this might not be the best, it just so happens that I feel a bit more comfortable using view controllers rather than straight-up views.

like image 166
Simon Goldeen Avatar answered Sep 19 '22 14:09

Simon Goldeen


Take a look at what Apple has to say on Controller Objects and the MVC design pattern

In iOS controller are generally expected to fill at least one the following roles:

  1. Coordinating controllers provide application specific logic. They respond to delegate messages, notifications, and IBActions. Coordinating controllers also setup connections between other objects and often manage the creation and destruction of those objects.

  2. View controllers, specifically UIViewControllers, manage the display of one "screen" worth of content and trigger transitions to the next "screen". They respond to memory warnings and rotation events.

  3. Mediating controllers exist in OS X but their role is usually filled by view controllers in iOS. They act as an intermediary between views and models; updating models when views receive input and updating views when models change.

If the behavior you are implementing fits into one of these categories you probably want to create a controller object. If your logic is only concerned with the display of data (and possibly responding to user input) then perhaps it belongs in the view layer. If your logic is about the data itself then it probably belongs in the model. If you can't find a good fit for your logic in any of those layers then you probably should model it differently as a combination of different responsibilities which belong on different objects in different layers. ie a view which requests data to display from a mediating view controller.

like image 45
Jonah Avatar answered Sep 22 '22 14:09

Jonah