Question

I'm having problems displaying the rightBarButtonItem of the Navigation Bar - I'm attempting to create it programmatically in the Application Delegate, where my UINavigationController is set up.

Code is as follows:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

// Override point for customization after application launch.
RSCListViewController *list = [[RSCListViewController alloc] initWithStyle:UITableViewStylePlain];
self.navController = [[UINavigationController alloc] initWithRootViewController:list];

UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithTitle:@"+"
                                                              style:UIBarButtonItemStylePlain
                                                             target:list
                                                             action:@selector(addPressed:)];

self.navController.navigationItem.rightBarButtonItem = barButton;

self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];

[DatabaseManager openDatabase];

return YES;
}

Running the application, no button item appears on the navigation bar.

I'm not sure whether I have missed something obvious - my attempts to rectify the problem using related Stack Overflow threads haven't yielded any success.

Any help appreciated.

Was it helpful?

Solution

You need to attach your bar button item to your custom view controller, not to the navigation controller. From Updating the Navigation Bar:

In addition, the navigation controller object builds the contents of the navigation bar dynamically using the navigation items (instances of the UINavigationItem class) associated with the view controllers on the navigation stack. To change the contents of the navigation bar, you must therefore configure the navigation items for your custom view controllers.

(...)

The navigation controller updates the right side of the navigation bar as follows:

  • If the new top-level view controller has a custom right bar button item, that item is displayed. To specify a custom right bar button item, set the rightBarButtonItem property of the view controller’s navigation item.

  • If no custom right bar button item is specified, the navigation bar displays nothing on the right side of the bar.

Therefore, replace:

self.navController.navigationItem.rightBarButtonItem = barButton;

with:

list.navigationItem.rightBarButtonItem = barButton;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top