loadView of UIViewController not called
I want to setup a UIViewController within a NavigationController programmatically, however the loadView nor vi开发者_开发技巧ewDidLoad method get called.
This is my code in the app delegate:
MyViewController *viewController = [[MyViewController alloc] init];
UIView *view = [[UIView alloc] initWithFrame:window.frame];
viewController.view = view;
UINavgationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[window addSubview:[navController view];
[window makeKeyAndVisible];
When I start the app I see a navigationbar, but no calls to loadView. What am I missing?
I thought loadView gets called after you call view
Edit
MyViewController *viewController = [[MyViewController alloc] init];
[viewController view]; // doesn't look right?
UINavgationController *navController = [[UINavigationController alloc] initWithRootViewController:viewController];
[window addSubview:[navController view];
[window makeKeyAndVisible];
edited towards Jonah's comment, but loadView still doesn't get called.
A UIViewController
will create its view (by loading it from a nib or implementing -loadView
) when the controller's view
getter is called and its view is currently nil
.
In the code shown you never invoke the view property's getter, only its setter.
Also, you are assigning the controller's view from your app delegate. UIViewController
s are expected to create their own views on demand, not have them provided by some other class. This approach will cause you problems later when you realize that the controller unloads its view and attempts to recreate it in response to memory warnings. Let your controller create its view, don't try to pass it one.
maybe you were not facing this issue... but the other day I ran into the same irritating trouble.. loadView, viewDidLoad and viewWillAppear not being called in my UIViewController.
My issue was v. simple but bit tricky to catch if you are not very careful. Instead of writing
-(void) loadView
I wrote:
-(void) loadview
Please note that this won't fire any warning. The difference of "V" and "v" in loadView can easily be missed. And obviously, since loadView didn't get called, viewDidLoad/viewWillAppear won't get called either as there was no view that got loaded (am not using any nib..creating the view programmatically).
-Anshu
Another gotcha worth noting is if you define a
@synthesize view;
without a matching @property in your implementation, this can result in calls to your view controller's returning nil, and no call to your loadView method.
精彩评论