4
votes

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.

6
Are you trying to create a modal view controller? - Aleksejs Mjaliks
Hi varundroid i am facing the same problem.. How did you resolve this.. If possible could you suggest me please - vinothp

6 Answers

5
votes

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.

5
votes

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];
3
votes

If you have your view controller being created from a NIB file in Interface Builder, and the view controller's design surface has a navigation bar on it, the easiest way to do this would be to drag a bar button item from the objects inspector right onto the navigation bar's right side. You would then create an IBAction in your header and implementation that you would hook up to.

1
votes

I achieve this inserting the button directly in the UINavigationBar:

[yourUINavBar insertSubview:yourButton atIndex:1];
0
votes

UIViewController's -navigationItem method does only work together with UINavigationController or other UIViewController containments. You will have to get access to the UINavigationBar and set the item directly.

0
votes

If you want to have a navigation bar, and have it work as you expect, create a UINavigationController using your UIViewController as the root view controller. Use that UINavigationController where you are using your UIViewController now.

Check out UINavigationController at developer.apple.com for more details.