Search code examples
objective-ciosuiviewuiviewcontrollerloadview

Correct method to programmatically create UIView and UIViewController and link together


I'm new to iOS development. To keep my iOS app nicely compartmentalised I'd like to create both the UIView and the UIViewController programatically, and tie them together once created.

So, I do the following: in my view controller I have this:

-(void)loadView {    
   NSLog(@"HPSMainMenuViewController loadView starting"); 
   HPSMainMenuView* mainmenuView = [[HPSMainMenuView alloc]initWithFrame:CGRectZero];
   self.view = mainmenuView; 
}

and in my View I have this:

-(id)initWithFrame:(CGRect)frame {
   self = [super initWithFrame:frame];
   if (self) {
      // Initialization code
      NSLog(@"HPSMainMenuView initWithFrame starting");
      [self setup];
   }
   return self; 
}
-(void)setup {

     UIButton* btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     btn.tag = E_PROFILE_BUTTON;
     [btn setTitle:@"Option1" forState:UIControlStateNormal];

     [self.view addSubview:btn ];

     btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
     btn.tag = E_CONTACTS_BUTTON;
     [btn setTitle:@"Option2" forState:UIControlStateNormal];

     [self.view addSubview:btn ];

     self.title = @"Hello"; 
}

Is this the right way to do this (given I want full programmatic control). It seems wrong to dynamically build the view within the ViewController hence my approach where I am building the view within an actual UIView class.

Lastly, I'm using loadView; should I be using viewDidLoad? If so, why?

Thanks very much.


Solution

  • What you are doing is correct, and actually good. Many developers keep their view controllers and views heavily tied together but if you want to keep them separate then that's great.

    loadView is where you should be creating and initializing everything. viewDidLoad can be called multiple times if the view is unloaded/reloaded due to memory warnings (for example). So viewDidLoad is where you would restore saved state, make your view correctly reflect your model, or any other initialization that you can't do in loadView.