Why doesn't initWithNibName work for my UIViewController subclass?

niels picture niels · Jul 1, 2009 · Viewed 41.5k times · Source

I have subclassed UIViewController into a new class, PageViewController (I'm writing a simple book app). I want to add a new view loaded from a nib file and am using the following code. It works.

PageViewController *viewController1 = [[UIViewController alloc] initWithNibName:@"Page1" bundle:nil];
[viewController1.view setUserInteractionEnabled:YES];
[self.view addSubview:viewController1.view];

However, the first line is wrong because I should be calling alloc on PageViewController. When I correct it (below), the code compiles but the xib file doesn't load and the view is just transparent.

    PageViewController *viewController1 = [[PageViewController alloc] initWithNibName:@"Page1" bundle:nil];
[viewController1.view setUserInteractionEnabled:YES];
[self.view addSubview:viewController1.view];

The PageViewController initWithNibName method has been uncommented and is just the default, setting self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil].

What I have tried: In the Page1 nib file, I have tried changing the File Owner class between PageViewController and UIViewController. Yes, I remembered to connect it back to the view outlet afterwards.

Help, please! I am stumped.

Answer

drvdijk picture drvdijk · Jul 1, 2009

Have you overridden the loadView method in PageViewController? What if you NSLog the viewController1.view?

Indeed, in Interface Builder, you have to set the file's owner to PageViewController, and connect its view to the view you have in Interface Builder.