neeraj
neeraj

Reputation: 1221

Instantiating View Controller from code - When is viewDidLoad called iOS

I am using something like:
VC = [[SettingsViewController alloc] initWithNibName:nil bundle:nil];

viewDidLoad is not called yet.
But when I do:
VC.view.frame = CGRectMake(...);

At this point viewDidLoad is called.

But the issue is, that the view dimensions that I am passing in the above code statement is not used in the viewDidLoad method.
I think it sees that view is being used, so it is time to load the view, and after loading the view it must be assigning the frame dimensions to the view. But what if I want that view dimensions set before viewDidLoad gets called, so that I can use those dimensions in the viewDidLoad method..
Something like initWithFrame..

Also, I don't have the view dimensions in the view controller. I have to assign the view dimensions from outside of the VC.
So probably after calling initWithNibName:bundle: method I can save the view frame dimensions in some variable.. but that doesn't look like a clean solution, does it?

Upvotes: 0

Views: 877

Answers (2)

tkanzakic
tkanzakic

Reputation: 5499

You can do something like this:

In the interface

@interface SettingsViewController : ... {
    CGRect _initialFrame;
}

...

- (id)initWithFrame:(CGRect)frame;

@end

In the implementation

- (id)initWithFrame:(CGRect)frame 
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        _initialFrame = frame;
    }

    return self;
}

- (void)viewDidLoad
{
    self.view.frame = _initialFrame;

    [super viewDidLoad];
}

and then from the class you use these controller:

VC = [[SettingsViewController alloc] initWithFrame:CGRectMake(...)];

Upvotes: 2

Bryan Chen
Bryan Chen

Reputation: 46608

viewDidLoad is called when the view did load. (surprise)

so by the time you call VC.view, before it return, the viewDidLoaded will be executed and then the view is returned, and set the frame.

so from your current approach, it is not possible

anyway, why you need view frame in viewDidLoad? maybe you can move that part into viewWillAppear / viewDidAppear which is only get called when the view is about to present

Upvotes: 3

Related Questions