views:

308

answers:

2

Hi,

I have a custom UIview which is created diagrammatically. How to associate to it a custom UIViewController (diagrammatically as well)

Thanks and regards,

+1  A: 

Say the view you created is called newView and the controller is newController. The simple approach would be:

newController.view = newView;

But I'd rather subclass UIViewController and override its - (void)loadView and - (void)viewDidLoad methods and create and/or manipulate the view there - that's the way Apple wants you to do it, and for good reason.

MrMage
but my custom view is a subview and its parent view has already a controller, how should I create the new controller?
AP
Where did you get that custom view from? Can't you recreate it from scratch? Note that when moving a subview to a new view (e.g. a new controller) it will disappear from the old view, so you should rather create a new view for the new controller.If you still want to assign an existing view to the new controller, just create the new controller as usual and then call `newController.view = newView;`, as I said before.
MrMage
+1  A: 

Implement loadView in the UIViewController to create a view hierarchy programmatically without a nib file.

- (void)loadView {
    // allocate the subclassed UIView, and set it as the UIViewController's main view
    self.view = [[[UIViewSubclass alloc] initWithFrame:CGRectMake(0, 0, 320, 460)] autorelease];
}

You can continue setting up the view/subview hierarchy in two ways. One is to add them in the custom UIView's initialization method, like so:

// in the MyView.m file
- (id)initWithFrame:(CGRect)f {
    if (self = [super initWithFrame:f]) {
        // add subviews here
    }
    return self;
}

The second way is to continue using the loadView method implemented in the UIViewController subclass, and just using [self.view addSubview:anotherView]. (Alternatively, use the viewDidLoad method in the UIViewController subclass.)

Note: Replace initWithFrame: with whatever the custom UIView's initialization method is (e.g., initWithDelegate:).

Arseniy Banayev
You have a memory leak in `loadView`. `view` is a retained property.
MrMage
Whoops, didn't notice that. Fixed!
Arseniy Banayev