Search code examples
iosuinavigationcontrolleruibarbuttonitemuitoolbaruinavigationitem

Add UIBarButtonItem to UIViewController pushed onto a UINavigation controller


I am trying to push a UIViewController onto a navigation controller and then add a UIBarButtonItem to the nav bar so i can use it to display a count down timer.

UINavigationController *navController = [[Session sharedInstance] getNavigationController];
GamePlayViewController *gameController = [[GamePlayViewController alloc] initWithNibName:@"GamePlayViewController" bundle:nil ];

UIBarButtonItem *timerBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

gameController.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:timerBtn, nil];

[navController pushViewController:gameController animated:YES];

When i use the code above its does not work. I also tried doing this from the ViewDidload method in the controller itself but no dice. I even tried to use rightBarButtonItem but get an error stating

 "to uncaught exception 'NSInvalidArgumentException', reason: 'Fixed and flexible space   items not allowed as individual navigation bar button item. Please use the leftBarButtonItems (that's plural) property.'
*** First throw call stack:"




UIBarButtonItem *timerBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

self.navigationItem.rightBarButtonItem = timerBtn;

Solution

  • If you go to IB and try to add a Flexible Space or Fixed Space, you will see the detail of these 2 objects that says that these 2 can only be added to a UIBarButtonItem that is being added to a UIToolBar, and not to a Navigation Bar!

    So I suggest you change your code to the following to start with:

    UIBarButtonItem *timerBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStylePlain target:nil action:nil];