Reputation: 29518
I have a LegendViewController that shows a legend. Originally, I just plopped an UIImageView in there. However now, we need a few legends and I want to reuse the LegendViewController. So I created a new initializer:
- (id)initWithView:(UIView *)view withNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
[self initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[self.view addSubview:view];
}
return self;
}
So now this works assuming I pass in a UIView object. For one of my legends, I was wondering if I could load a .xib into my view controller without an image or a UIView object. I have a very simple legend where I just want some color coded squares (UIViews with colors), and some text (UILabels). I can create this in a standalone .xib file, but I wasn't sure how I could load it into my LegendViewController. I've got so far as:
UINib *nib = [UINib nibWithNibName:@"HealthLegend" bundle:nil];
where HealthLegend is my standalone .xib file with my data. Or can this not be done and I need to either create an image in some drawing program, or draw the code manually in drawRect? Thanks.
Upvotes: 0
Views: 392
Reputation: 2083
From the reference guide
When you create an UINib object using the contents of a nib file, the object loads the object graph in the referenced nib file, but it does not yet unarchive it. To unarchive all of the nib data and thus truly instantiate the nib your application calls the instantiateWithOwner:options: method on the UINib object
UINib object can provide a significant performance improvement
So I guess you want something like:
UINib *nib = [UINib nibWithNibName:@"HealthLegend" bundle:nil];
NSArray *views = [nib instantiateWithOwner:nil options:nil];
UIView *view = [views objectAtIndex:0];
Upvotes: 0
Reputation: 38728
You can load a nib like this
NSArray *topLevelObjects = [[NSBundle bundleForClass:[self class]] loadNibNamed:@"HealthLegend"
owner:nil
options:nil];
// Assuming you only have one root object in your nib
[self.view addSubview:[topLevelObjects objectAtIndex:0];
Change the owner to the appropriate object depending on what you set the File's Owner
to in the nib (if that's even required - sounds like you have a static view so it may not be)
Upvotes: 1