UIViewController initWithNibName results in nil vi

2019-08-24 17:50发布

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.

4条回答
2楼-- · 2019-08-24 18:13

Check the following:

  1. Both XIB_iPad.xib and XIB_iPhone.xib exist in your project.
  2. Each xib file's "File owner" is of the correct class (YourViewController).
  3. 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.

查看更多
不美不萌又怎样
3楼-- · 2019-08-24 18:21

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楼-- · 2019-08-24 18:25

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.

enter image description here

查看更多
唯我独甜
5楼-- · 2019-08-24 18:28

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?

查看更多
登录 后发表回答