Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - how to create a navigation bar item in view controller?

I have been trying to create a navigation bar back button.

Here is my code :-

UIBarButtonItem *barButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:nil]autorelease];
self.navigationItem.rightBarButtonItem = barButton;

But it isn't displaying anything on navigation bar.

I am using UIViewController, not an UINavigationController.

Is UINavigationController is the only way to achieve this?

Any help would be really appreciated.

Any link to a good tutorial will be great.

Thanks.

like image 205
Varundroid Avatar asked Dec 09 '22 06:12

Varundroid


2 Answers

Without the viewcontroller having a navigation controller (i.e viewController.navigationController != nil) you cannot add it in this manner.

One thing you can do is if it is being created by the nib is to just drag a bar button item into a navigation bar and link it via IBAction.

like image 126
Kaiser Avatar answered Feb 17 '23 15:02

Kaiser


I'd recommend pushing this view controller out of a nvigationcontroller - you will get all those things for free:

UIViewController *vc = [[UIViewController alloc] initWithNibName:nil bundle:nil];
UINavigationController *navCntrl1 = [[UINavigationController alloc] initWithRootViewController:vc];
like image 39
TommyG Avatar answered Feb 17 '23 13:02

TommyG