uiviewcontrolleruinavigationbaruibarbuttonitemuiscenedelegate

Does adding a bar button item to the navigation bar programmatically when offering scene support differ from the old app delegate approach


I have used the following code for years to add a right bar button item to the navigation bar, but for some unknown reason, this no longer works. It stopped working when I updated my app to have Scene support. I don't understand what is preventing this code from working.

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"viewDidLoad");

    // Add a Share Button
    UIBarButtonItem *shareButton;
    shareButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(editProject:)];

    self.navigationItem.rightBarButtonItem = shareButton;
    
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor blueColor];
}

-(void) editProject:(id)sender {

}
@end

To test this, I created a brand new test app that does nothing except for attempting to add this button. The autogenerated code gives you the following project and I simply modified the ViewController class as shown above:

Project Navigator and Storyboard

What do I need to do differently to make the right bar button item to display?


Solution

  • Ok, now I understand. In my original project, I mistakenly made my root view controller be the initial controller when I was upgrading to a scene lifecycle. Unlike this test project, my original app had a navigation controller and when I made my root view controller be the initial controller, it removed the initial controller status from the navigation controller. That prevented the navigation bar item from working. So in this test project, once I added a navigation controller and made the ViewController have a "root view controller" relationship to the navigation controller, then it works.