iosobjective-cxibaddsubviewloadnibnamed

Only white rectangle appears after adding a subview


I'm trying to add a subview with this code:

NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"subView" owner:self options:nil];
SubView *subView = [subviewArray objectAtIndex:0];
[self.view addSubview:subView];

But only a white rectangle appears, however with the correct size. The SubView's initialization methods aren't called at all. (The initWithCoder:(NSCoder *)aDecoder should be called in this case, but isn't.)

The xib's owner is the SubView class. This is a view and not a controller.

What could cause this malfunction, and what would be the proper solution?


Solution

  • Use the following code to create view from xib:

    UINib *menuNib = [UINib nibWithNibName:@"MenuView" bundle:nil];
    NSArray *aNib = [menuNib instantiateWithOwner:self options:nil];
    UIView *menuView = [aNib objectAtIndex:0];