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];
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With