Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIViewController vs. UIView - which one should create subviews?

I'm trying to wrap my head around the roles of UIViews and UIViewControllers. If I'm creating and inserting subviews programmatically, is it typical to do this from the view or the controller?

I'm really just wondering if there's a convention/pattern for this. In my sample application, I'm loading 50 images at runtime, adding them as subviews to the main view, then letting the user drag them around the screen. I'm currently doing all the initialization in the view's initWithCoder:

- (id)initWithCoder:(NSCoder*)coder 
{
    if (self = [super initWithCoder:coder]) {
      // load UIImageViews and add them to the subview
    }

    return self;
}

The view also implements touchesBegan/touchesMoved to allow dragging. My problem comes when I try to access [self frame].size in initWithCoder, it doesn't seem to be initialized yet. This makes me think I may be loading the images in the wrong place...

like image 499
Chris Karcher Avatar asked Nov 11 '08 04:11

Chris Karcher


3 Answers

It depends on what you're doing. If the view represents something "packaged", then you create subviews from the view itself. If you're merely aggregating views together, then you should do it from the view controller.

Think about traditional encapsulation. Is your subview conceptually "part" of its superview, or does it just live there in the drawing hierarchy?

like image 113
Jim Puls Avatar answered Nov 14 '22 09:11

Jim Puls


Suppose you're creating a view that contains some controls, like to edit a record with multiple fields or something. Since you're going to be using those text fields and their data in the view controller, they conceptually "belong" to the view controller, and the parent view exists just for grouping and layout purposes. This is probably the more common scenario.

If you were creating a view subclass to behave like a new control, for example, then I would say you should create and manage the views entirely within the view class. I imagine this case will happen less frequently in practice.

like image 2
Alex Avatar answered Nov 14 '22 09:11

Alex


It sounds like you may be adding them in the wrong place. If you moved the addition of the subviews into the ViewController, then you could do this work on viewDidLoad and you'd be guaranteed that the main view was already initialized and ready to access.

like image 2
Bdebeez Avatar answered Nov 14 '22 10:11

Bdebeez