Reputation: 8794
I have created a custom view hierarchy in an XIB that I want to place on various other view controller's view. The hints from SO indicate that I have to explicitly add as a subview. The XIB loads and viewing it in the debugger, it looks correct, however, there are two problems. First, it only defines the toplevel UIView of my custom XIB and that does not display. I have purposely put a different color background to make it obvious. The code for the parent "OtherViewController" that is trying to load this custom view as its header is as follows:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
NSLog(@"%s", __FUNCTION__ );
if (self) {
// Custom initialization
appDelegate = (myProjectAppDelegate*) [[UIApplication sharedApplication] delegate];
NSObject *obj = [[NSBundle mainBundle] loadNibNamed:@"PageHeaderView" owner:self options:nil];
NSArray *array = nil;
if ([obj isKindOfClass:[NSArray class]]) {
array = (NSArray*) obj;
for (UIView *customView in array) {
NSLog(@"%@", customView);
if ((customView.tag == 3700) && ([customView isKindOfClass:[PageHeaderView class]])) {
[self setCustomPageHeaderView: (PageHeaderView*) customView];
[self.view addSubview: customPageHeaderView];
[self.view bringSubviewToFront: customView];
}
NSArray *array = [self.customPageHeaderView subviews];
for (NSObject *obj in array) {
NSLog(@"%s: \t%@", __FUNCTION__, obj);
}
}
} else {
NSLog(@"%s: object following loadNibNamed is [%@]", __FUNCTION__, [obj class]);
}
}
return self;
}
The TAG = 3700 was again to have an obvious bit of information in the debugger. It shows up in the custom view as expected.
Upvotes: 1
Views: 2003
Reputation: 17918
When you access the self.view
property for the first time, the view controller lazy-loads its view by calling loadView
, which loads the view from a NIB by default. By accessing self.view
within your initWithNibName:bundle:
method, you're asking the view controller to load its view before the controller has even finished initializing.
Try moving this code to viewDidLoad:
. That will guarantee that self.view
has already been lazy-loaded by the time you access it.
Upvotes: 3