UIViewController vs. UIView - which one should I create?

I am trying to wrap my head around the roles of UIViews and UIViewControllers. If I create and paste subviews programmatically, is it typical to do this from a view or controller?

I'm just wondering if there is an agreement / pattern for this. In my sample application, I load 50 images at runtime, adding them as subzones to the main view, and then letting the user drag and drop them around the screen. I am currently doing initialization in the initWithCoder view:

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

The view also implements Began / touchhesMoved strokes that allow you to drag and drop. My problem arises when I try to access [self frame] .size in initWithCoder but it is not initialized yet. It makes me think that I can upload images in the wrong place ...

+6
iphone cocoa-touch
source share
4 answers

It depends on what you do. If the view represents something "packaged", then you create subviews from the view itself. If you simply combine the views together, then you must do this from the view controller.

Think of traditional encapsulation. Is your subview conceptually a โ€œpartโ€ of its supervisor or does it just live there in the drawing hierarchy?

+7
source share

Suppose you create a view containing some controls, for example, to edit an entry with multiple fields or something else. Since you are going to use these text fields and their data in the view controller, they conceptually โ€œbelongโ€ to the view controller, and the parent view exists only for grouping and layout purposes. This is probably a more common scenario.

If you created a subclass of the view to behave like a new control, for example, then I would say that you must create and manage views completely in the view class. I suggest that this case will happen less often in practice.

+2
source share

It looks like you can add them to the wrong place. If you moved the addition of views to the ViewController, you could do this work on viewDidLoad, and you are guaranteed that the main view has already been initialized and is ready to access.

+2
source share

The damming explanation would be:

Subclass UIViewController whenever you plan to display the view as modal (presentModalViewController) or inside a UINavigationController (pushViewController)

A subclass of UIView when it is a small component inside the main view ... for example, you want to make a custom button or ...

More specifically in your example ... if you initialize UIViewControllers, you can set view properties, for example. like frame size only after your view is added to the supervisor. Only at this moment does the UIViewController load and initialize its view.

I think in your case you should use UIViews ... you can set the frame size right after selecting and initializing them.

+1
source share

All Articles