aryaxt
aryaxt

Reputation: 77596

iOS - UINavigationController and adding a left bar button?

The following mwthod is the delegate method of a UINavigationController. I want to be abel to decide whether to add the left item to each page or not. The code below doesn't work, am I doing something wrong?

I don't want to perform this through the ViewController itself. I want the NavigationCopntroller to be responsible for this task.

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
                                                                                  target:self 
                                                                                  action:@selector(menuItemSelected:)];
    [self.navigationItem setLeftBarButtonItem:menuItem];

    // I also tried 
    // [viewController.navigationItem setLeftBarButtonItem:menuItem];
}

Upvotes: 0

Views: 5938

Answers (2)

aryaxt
aryaxt

Reputation: 77596

There was a warning in console saying that "Nested Push could corrupt the navigationController" I was pushing 2 Viewcontroller into the stack, instead of pushing 1 viewController at a time.

Fixing this problem and getting rid of the warning fixed this problem as well.

Upvotes: 1

Ecarrion
Ecarrion

Reputation: 4950

I think that the problem is that you're trying to acces the navigationItem property on the viewController but it doesn't exist because in the willShowViewController method the viewController is not in the navigationController stack yet, try using the didShowViewController delegate method

Like this:

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
    UIBarButtonItem *menuItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemOrganize 
                                                                                  target:self 
                                                                                  action:@selector(menuItemSelected:)];
    [self.navigationItem setLeftBarButtonItem:menuItem];

    [viewController.navigationItem setLeftBarButtonItem:menuItem]; 

}

Upvotes: 1

Related Questions