Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add items to NavigationBar (Not using UINavigationController)

I have a UIViewController with a UITableView in it, and also added a UINavigationBar. How can I add and "edit" button and a "+" button in that bar programmatically? (I have tried using IB, but the title is always replaced, and not other items are added) I am not using a UINavigationController. is my UIViewController standing alone.

This is what I have tried without success:

UIBarButtonItem *barButton = 
    [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonItemStyleBordered 
                                                  target:nil
                                                  action:nil];
UINavigationItem *editItem = [[UINavigationItem alloc] initWithTitle:@"Title"];
[editItem setLeftBarButtonItem:barButton animated:YES];
[navigationBar setItems:[NSArray arrayWithObject:editItem] animated:YES];
like image 731
nacho4d Avatar asked Aug 31 '10 05:08

nacho4d


2 Answers

Your UIViewController has a navigationItem property. You can set the left and right bar button items with self.navigationItem.leftBarButtonItem = ... and self.navigationItem.rightBarButtonItem = ...

Edit:

OK, I assume you have a reference to your UINavigationBar? Then I guess you'd add a single UINavigationItem to it:

UINavigationItem *item = [[UINavigationItem alloc] initWithTitle:@"A Title"];
theNavigationBar.items = [NSArray arrayWithObject:item];
[item release]; // or keep this as an instance variable

and then set that item's left and right buttons:

theNavigationBar.topItem.leftBarButtonItem = ...;
theNavigationBar.topItem.rightBarButtonItem = ...;

I haven't tried this, but I think it should work.

like image 154
Thomas Müller Avatar answered Oct 18 '22 15:10

Thomas Müller


UIBarButtonItem *leftBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(theEditMethod:)];      
[viewController.navigationItem setLeftBarButtonItem:leftBarButton animated:NO];
[leftBarButton release];

UIBarButtonItem *rightBarButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(theAddMethod:)];       
[viewController.navigationItem setLeftBarButtonItem:rightBarButton animated:NO];
[rightBarButton release];
like image 27
vfn Avatar answered Oct 18 '22 16:10

vfn