问题
I'm trying to make a view controller that will always load the same nib. My initialization code looks like this:
-(id)init
{
NSString* nibName;
if(UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
nibName = @"XIB_iPad";
else
nibName = @"XIB_iPhone";
self = [super initWithNibName:nibName bundle:nil];
if (self)
{
...
}
return self;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
return [self init];
}
The problem is that this code results in the view controller having a nil view. Is there something I'm doing wrong here? Is there a better way to do this?
Thanks.
回答1:
Check the following:
- Both XIB_iPad.xib and XIB_iPhone.xib exist in your project.
- Each xib file's "File owner" is of the correct class (YourViewController).
- Each File Owner view outlet (in the xib files) is linked correctly to a view.
If you keep having problems after you check these three steps, please provide with the code you use to instantiate and setup your custom view controller.
回答2:
I had the same problem.
I checked all options as chosen answer says and didn't solve the problem for me.
My problem was that the auto layout for the view was enabled (but I don't know why, because of this feature, the view always came as nil; if someone knows, please comment).
To disable auto layout, go to "File Inspector" and uncheck option "Use Autolayout" (see figure).
Hope help someone.
回答3:
One bit of caution is that if you pass nil
for nibName
, according to the documentation, do a search in this order (emphasis added):
If the view controller class name ends with the word “Controller”, as in MyViewController, it looks for a nib file whose name matches the class name without the word “Controller”, as in MyView.nib.
It looks for a nib file whose name matches the name of the view controller class. For example, if the class name is MyViewController, it looks for a MyViewController.nib file.
I had a plain vanilla view that had basically the same name without "Controller" suffixed at the end. It was loading this instead of the intended nib.
回答4:
Your code looks right to me. Is it possible that your XIB files are named differently (case matters on the device), and that they're members of the correct target?
来源:https://stackoverflow.com/questions/10770796/uiviewcontroller-initwithnibname-results-in-nil-view