Eyal
Eyal

Reputation: 10828

UINavigationController subclass with custom back button

I know I can set custom back button from the view controller itself, something like:

- (void)setBackButton
{
    UINavigationBar* navBar = self.navigationController.navigationBar;
    UIButton* backButton = [navBar backButtonWith:[UIImage imageNamed:@"navigationBarBackButton.png"] 
                                        highlight:nil 
                                     leftCapWidth:14.0];

    [backButton addTarget:self action:@selector(backButtonTapped:) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:backButton] autorelease];
}

- (void)backButtonTapped:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}  

The problem is that I need to do it for all my view controllers...
One solution is to put this code in some BasicViewController and all my view controllers will subclass it.

But my question is can I subclass the UINavigationCotroller itself and set it's nab bar left button to this custom button?

Upvotes: 1

Views: 1804

Answers (2)

Joshua Weinberg
Joshua Weinberg

Reputation: 28688

The right way to do this is using UIAppearance

It provides methods on UIBarButtonItem such as

- (void)setBackButtonBackgroundImage:(UIImage *)backgroundImage forState:(UIControlState)state barMetrics:(UIBarMetrics)barMetrics

and

- (void)setBackButtonBackgroundVerticalPositionAdjustment:(CGFloat)adjustment forBarMetrics:(UIBarMetrics)barMetrics

Upvotes: 2

Christian
Christian

Reputation: 1714

No. It would be better to have a custom UIViewController that handles this behavior.

Upvotes: 1

Related Questions