objective-cnibuinib

init or initWithNibName not getting called when loading nib file manually


I am loading the nib file manually (for UIView reusability), the code for loading the nib file

- (NSArray*)loadMyNibFile
{
    UINib *nib = [UINib nibWithNibName:@"customView" bundle:nil];
    NSArray *topLevelObjs =  [nib instantiateWithOwner:self options:nil];

    NSLog(@"objects: %@", topLevelObjs);

    return topLevelObjs;
}

after loading the nib name i am adding it to a UIScrollView

NSArray *array = [self loadMyNibFile];
CustomView *view = [array objectAtIndex:0];
CGRect frame = CGRectMake(0, 0, 320, 216);
frame.origin.x = self.scrollView.frame.size.width * 2;
frame.origin.y = 99;
[view setFrame:frame];
[self.scrollView addSubview:view];

not the problems is that when I load the nib file this way the init and initWithNibName methods are not being called, how could this be solved ?

Thank you in advance,


Solution

  • You should override [UIView initWithFrame:] and [UIView initWithCoder:] methods (see the UIView Class Reference).

    If you always load the view from a NIB, as opposed to manual creation, it's probably better to override awakeFromNib (see reference).