Using a subclass of UIViewController subclass with subclass of UIView subclass

541 views Asked by At

I have an MVC architecture of a certain view within my app. Now I want to create a subclass of the View and Controller part. The original UIViewController subclass is loaded with a UIView subclass from storyboard. How can I make my subclass of this UIViewController subclass use my subclass of the UIView subclass code when it loads its view?

EDIT

Here's some more details about what I want to do. I currently have these classes:

ControlView
ControlViewController

which are connected with storyboard. I load an instance of ControlViewController using:

self.storyboard!.instantiateViewControllerWithIdentifier("ControlViewController")! as! ControlViewController

Now what I want to do is subclass ControlView so that I can change some constraints and add a few extra subviews. Let's call this subclass ExpandedControlView. I also want to subclass ControlViewController because I want to add some extra actions from ExpandedControlView to the controller. This can be called ExpandedControlViewController.

Then I want to be able to instantiate ExpandedControlViewController and use ExpandedControlView like ControlViewController would with ControlView.

2

There are 2 answers

3
dave234 On

In storyboard, select the hierarchy view.

Select hierarchy view

Then select your UIViewController's View in the hierarchy on the left, and select that view's class in the identity inspector on the right. Hierachy View

Or if you want to do it in code. Override viewDidLoad on ControlViewController, instantiate your custom view and set your ControlViewController's view property to your custom view.

-(void)loadView{
    ControlView *myCustomView = [[ControlView alloc]initWithFrame:[UIScreen mainScreen].applicationFrame];
    self.view = myCustomView;
}

One caveat when doing this is that the layout of any subviews might change from the time loadView is called. So if you have subviews in your custom view, you should also override layoutSubviews in your custom view and set all your view's subviews' frame property again there.

0
Tushar On

Implement loadView in your view controller subclass and set the view property with instance of your custom view subclass.