1

I am looking to replace the back button in the UINavigationController throughout my application. My requirements is that this back button be defined in one XIB and if possible, the code to set it is in one place.

I have seen various methods that set the property self.navigationItem.backBarButtonItem to be a UIBarButtomItem with the custom button as it's view, e.g. [[UIBarButtonItem alloc] initWithCustomView:myButton];

My first thought was to create a global category (not sure if that's the term, I'm new to Objective-C as you might have guessed) that implements 'ViewDidLoad' for all my UINavigationControllers, and setting this property. My problem is loading the XIB to this button that I create at runtime.

Does anyone have a suggestion on a neat way of doing this (I guess it must be a common thing to do, and I can't imagine repeating code in all my screens). I have considered creating a UINavigationController subclass, however I wasn't sure how this would effect my custom implementations of ViewDidLoad.

Any advice much appreciated. Also I need to target >= iOS4 (the appearance API is iOS5 only).

Community
  • 1
  • 1
Marc
  • 1,541
  • 2
  • 19
  • 29

2 Answers2

4

I prefer to not force inheritance where possible so you could do this with two categories

@interface UIViewController (backButtonAdditions)

- (void)ps_addBackbutton;

@end

@implementation UIViewController (backButtonAdditions)

- (void)ps_addBackbutton;
{
    // add back button
}

@end

@interface UINavigationController (backButtonAdditions)

- (void)ps_pushViewController:(UIViewController *)viewController animated:(BOOL)animated;

@end

@implementation UINavigationController (backButtonAdditions)

- (void)ps_pushViewController:(UIViewController *)viewController animated:(BOOL)animated;
{
    [viewController ps_addBackbutton];
    [self pushViewController:viewController animated:animated];
}

@end

Now #import these files as appropriate and instead of using

[self.navigationController pushViewController:aViewController YES];

use

[self.navigationController ps_pushViewController:aViewController YES];

Disclaimer

I free styled this in the browser so you may need to tweak it

Paul.s
  • 38,494
  • 5
  • 70
  • 88
0

I had the same issue in my current project, the solution I came up with was to create a MYBaseViewController base class without xib and there in viewDidLoad programmatically (if you want to init barButtonItem with custom view, you are not able to create in xib anyways) create a customBackButton (and of course release it and set to nil viewDidUnload.

This works good for me because this way I can create xibs for all my other viewControllers that are subclasses of MYBaseViewController(if you created a view for base class in nib you would not be able to create a nib for a subclass).

dariaa
  • 6,285
  • 4
  • 42
  • 58