Search code examples
iosuinavigationitem

Adding a custom UIView to a UINavigationItem


I have 3 buttons that I am trying to add as a custom header to some of the views in my application. Adding them in the storyboard works just fine and I can hook them up to methods in the view controller.

I recently wanted to add these buttons to some other pages and wanted to abstract them out into a control that could be re-used on the different pages. I have it setup but am having difficulty adding it using the normal method.

Maybe this picture will help explain what I'm talking about

Typically I add the view controller as a child view controller and then add the view as a subview, in this case I'm adding it to a placeholder that I have in the storyboard, code looks like this:

// Setup Header
HeaderViewController * headerViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"HeaderViewController"];
[headerViewController.view setFrame:CGRectMake(0.0f, 0.0f, [headerViewController.view frame].size.width, [headerViewController.view frame].size.width)];
[_headerView addSubview:headerViewController.view];

This allows me to have the view looking correct however when I click on a button it crashes because it can't find the view controller that has the IBActions associated with the button click. Normally I would add the following code and it would be taken care of:

[self addChildViewController:headerViewController];

In this case however I get an error stating:

Terminating app due to uncaught exception 'UIViewControllerHierarchyInconsistency', reason: 'child view controller: should have parent view controller: but actual parent is:'

I understand this to mean that it thinks the parent of the custom header view controller should be navigation controller, setting it as a child of the navigation controller doesn't work either. It adds the header view on top of the PageViewControllers view being displayed. I'm probably missing something simple

Some of the combinations that I've tried work on the simulator but none of them work on the device, so if you play around with a similar configuration make sure to look at it on device if it appears to be working in the simulator.

Any thoughts or what information other information could be provided to help?


Solution

  • I was unable to get this working using other methods suggested, not that they're wrong I just couldn't get them to work.

    I ended up creating a UIView subclass with a corresponding xib and put the IBActions into the UIView subclass. This required a weak link to the holding view controller in order to show the modal views appropriately for the IBAction triggered.