Reputation: 5323
I have a custom UIview which is created programmatically. How to associate to it a custom UIViewController (programmatically as well)
Thanks and regards,
Upvotes: 1
Views: 1864
Reputation: 694
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:
).
Upvotes: 5
Reputation: 7486
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.
Upvotes: 1