views:

9814

answers:

3

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...

+3  A: 

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?

Jim Puls
I've updated the question with more information. In my case, the view is just part of the hierarchy but it also implements the touchesBegan/touchesMoved to allow dragging.
Chris Karcher
After some reading, it looks like controller itself can actually respond to these events, in which case I can do everything from the controller.
Chris Karcher
+1  A: 

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.

Alex
+1  A: 

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.

Bdebeez