Reputation: 26546
I have read in multiple places that only one UIViewController
should be on screen at a time. But I don't quite understand how to accomplish what I need otherwise.
Imagine the weather app. There is a single view controller with a scroll view, to which multiple views are added (the weather panels). Presumably these are all added and managed by the main UIViewController
, which is also responsible for scrolling, etc.
But imagine each of those weather panels was instead a CarView
, each with data about a specific type of car, and some controls to edit that data.
Wouldn't it make sense to have a series of CarViewControllers
, each with a Car
property that they can manipulate? Each CarViewController
would be responsible for it's car data object, it's view, and glueing them together, and the main view controller would simply be responsible for adding each carViewController.view
to its scrollview.
Isn't this better for re-usability and encapsulation? Not to mention more convenient.
Upvotes: 2
Views: 1466
Reputation: 26546
It seems like this now explicitly supported in iOS 5 using a container view controller.
There are not a lot of resources yet that discuss it, but this WWDC session is useful.
This question also provides some resources.
Upvotes: 0
Reputation: 18363
I think it just comes down to whether it will make your life easier or not. One alternative I like to do is to just write composite UIView
subclasses specifically for displaying a "conceptual" model - like a car - and then write categories on them to populate the view information using a specific model implementation. That way you can re-use the view when changing your model but still keep some of the logic from cluttering up the view controller. I try to reserve a view controller for something like radically different views toggled with a UISegmentedControl
or something.
Edit: an example of a UIView
and its populating category.
@interface CarView : UIView
@property (strong) UILabel *modelLabel;
@property (strong) UILabel *makeLabel;
@property (strong) UILabel *yearLabel;
//etc
@end
Then you have a model-specific category, that while a category on the view really fits more into the controller layer; while a little bit of a breach of MVC I think it works nicely from a responsibility assignment standpoint, doesn't couple your main view implementation to any data implementation, and keeps your view controllers leaner, so I think it's worth the tradeoff.
@interface CarView (CarEntityPopulating)
- (void)populateFieldsWithEntity:(NSManagedObject *)entity;
@end
@implementation CarView (CarEntityPopulating)
- (void)populateFieldsWithEntity:(NSManagedObject *)entity
{
self.modelLabel.text = [entity valueForKey:@"name"];
self.makeLabel.text = [[entity valueForKey:@"make"] valueForKey:@"name"];
self.yearLabel.text = [[entity valueForKey:@"year"] stringValue];
//etc....
}
Upvotes: 1