views:

146

answers:

2

.Hi,

I have a nib file that contains an header that will be used in most of my views, so that I can change it's layout just once when I need. I'd like to know if it's possible to add the header nib view with interface builder, or if I need to do that programmatically and how should it be done.

I've thought about setting the subclass of the subview to a UIView subclass that automatically loads the nib file.

- (id)initWithFrame:(CGRect)frame {

    UIView *cell;

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed: @"MainHeaderView"
                                                 owner: self
                                               options: nil];

    for (id oneObject in nib) 
        if ([oneObject isKindOfClass: [UIView class]]) 
            cell = (UIView *) oneObject;

    if ((self = [super initWithFrame: [cell frame]])) {
        // Initialization code
    }
    return self;
}

But this also doesn't seem to work.

A: 

It should work, at least in theory. For that matter, it should be possible (but with rather a lot of effort) to add it via IB, from what used to be called a palette, a long time ago; I believe that option was recreated.

I would say that loading from initWithFrame: is likely not to work. Other possible places to load would be awakeFromNib (with a caveat about multiple nib loadings causing it to be called multiple times), or viewDidLoad. Try moving the load to viewDidLoad, and see if your cell is connected up. You should also be testing for failure to load the nib (nil return).

Paul Lynch
A: 

Ok, I've solved this another way.

I've created the headerView and the controller, and a subclass of UIViewController for all views that needed the header to be displayed, loading them all with the header. Something like this:

@implementation MyDefaultViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    MyTestAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    [self.view addSubview: [appDelegate.headerViewController view]];
}

Every view that needs the header to be there will have a controller that's a subclass of MyDefaultViewController. Seems to work, although the fact that I don't specify where to place the header scares me a bit xD

Tiago