Matt Zera
Matt Zera

Reputation: 465

Where is the best place to put setup code for a UIViewController;

I've just gotten too frustrated with interface builder and I'm trying to create my view controllers in code. I've managed to setup the window and create a navigation controller and add it as the root view controller...

I'm not quite sure where I should start adding buttons and setting their targets...

Should I put the code for doing that in my subclasses of UIViewController or would somewhere else be better?

Also once I've done that... What is the best place to put auto-layout constraints?

Any help would be appreciated.

Upvotes: 3

Views: 885

Answers (3)

Justin Meiners
Justin Meiners

Reputation: 11113

Each view controller subclass should create and release its own buttons, controls, subviews etc.

You can do all view controller setup by overriding this UIViewController method

- (void)viewDidLoad
{
   [super viewDidLoad];
   ...
   UIButton* newButton = [UIButton buttonWithType:...];
   // other button config (including constraints)
   [self addSubview:newButton];
   ...
   // create and setup other subviews
}

Upvotes: 4

Matt Zera
Matt Zera

Reputation: 465

Thank you so much for trying to help me. I've been searching the apple documentation on the subject and just discovered that apple wants you to override the loadView method of the UIViewController and set up the entire view there. They even said something about setting up the constraints. I think you can set them up in view did load since if you don't override the function it gives you an empty view but I think I'll be safe and do it the way apple says to do it.

I'm sorry if i've waisted your time. I should have looked more before asking the question.

- (void)loadView
{
    CGRect applicationFrame = [[UIScreen mainScreen] applicationFrame];
    UIView *contentView = [[UIView alloc] initWithFrame:applicationFrame];
    contentView.backgroundColor = [UIColor blackColor];
    self.view = contentView;

    levelView = [[LevelView alloc] initWithFrame:applicationFrame viewController:self];
    [self.view addSubview:levelView];
}

Upvotes: 0

rmaddy
rmaddy

Reputation: 318824

Each view controller should be its own custom class that extends UIViewController (or UITableViewController, etc.). This way all of the logic of each view controller is contained in its own class.

What I do is override viewDidLoad (don't forget to call [super viewDidLoad];) to create, setup, and add all of the subviews needed by the view controller. This is also where you would setup each subview's constraints or autoresizing masks.

If you need to do any custom layout, do that in the viewWillLayoutSubviews method.

Upvotes: 2

Related Questions