Jaymit Desai
Jaymit Desai

Reputation: 153

Where to initialize subview?

I am new to iOS development and I am currently reading the book : iOS Programming (Objective C) by Big Nerd Ranch.

I am confused as in where to initialize subviews such as UIButtons, UIImageView while creating views programtically:

or

I have seen both the approaches being used in various stackoverflow posts but no post that explains which approach is the right one.

Upvotes: 0

Views: 711

Answers (2)

facumenzella
facumenzella

Reputation: 559

It dependes on which architecture you are using. Apple raises the flag of Model-View-Controller, but in fact, UIViewControllers are the View. For Example: Let's say that you have a pretty LoginViewController. When you instantiate it, you will be doing something like

LoginViewController *loginVC = [[LoginViewController alloc] init];

At this point, no view is loaded. Your ViewController has just executed the init method, nothing else. When the system calls

loginVC.view

the first method to be executed will be

- (void)loadView;

there you should do exactly that, load your view. So, the approach i like is to have an additional LoginView.

- (void)loadView
{
   // you should have a property @property (nonatomic, strong) LoginView *loginView;
   self.loginView = [[LoginView alloc] init];
   self.view = self.loginView;
}

and in the LoginView init method, you should put your code to build up the view.

However, you could eliminate LoginView, and instantiate all your subviews like this:

- (void)loadView
{
   self.view = [[UIView alloc] init];
   UIButton *button = [[UIButton alloc] initWithTargetBlaBlaBla...];
   [self.view addSubview:button];
   // add more fancy subviews
}

In my experience, the first approach is much cleaner than the second one. It also makes version control a lot easier (try to merge a xib, I dare you). I always use MyView.m to build the view (a.k.a setup constriants, style) and use MyViewController.m things like animations, lifeCycle. I like to think that MyView.m is the programatic xib, so anything that you can do with xibs, you should me able to do it inside your view.

Hope it helps!!

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27438

you can initialize as per your app's requirement. If any view or button or anything is part of initial setup of your app then you should initialize it in viewDidload.

Now, for example there is requirement like user press button and then new view will be created then you can initialize view in button's click method etc.

So, it's depends on your requirement.

Static views which will live from start to and of app should be initialize in viewdidload, because this is the first method getting called of viewcontroller.

hope this will help :)

Upvotes: 2

Related Questions