Search code examples
uinavigationbaruibarbuttonitem

How to add UINavigationBar with two UIBarButtonItem programmatically?


I added code to the viewDidLoad method of ViewController. I have two UIBarButtonItem, one of them is on the left called Left and the other one is at the right called Right. I can get the left button to work but I cannot even see the right button. What am I doing wrong?

UINavigationBar *navbar = [[UINavigationBar alloc]initWithFrame:CGRectMake(0, 0, 420,           44)];
[navbar setBackgroundImage:[UIImage imageNamed:@"bg_fade.png"]     forBarMetrics:UIBarMetricsDefault];
UINavigationItem *item = [[UINavigationItem alloc]initWithTitle:@"Tray Tracker"];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithTitle:@"Left" style:UIBarButtonItemStylePlain target:self action:
                            @selector(leftAction:)];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithTitle:@"Right" style:UIBarButtonItemStylePlain target:self action:
                               @selector(saveAction:)];
item.leftBarButtonItem = leftButton;
item.rightBarButtonItem = rightButton;
navbar.items = @[item];
[self.view addSubview:navbar];

I do have the IBActions for leftAction and saveAction

swcreenshot


Solution

  • If you simply want a bar with two buttons, you should use a UIToolbar instead. It's much easier to handle for this simple case. The only change you would need is to create a UIBarButtonItem flexibleSpace (it's a system item), and call [toolbar setItems:@[leftButton, flexibleSpace, rightButton]];

    If you need actual navigation functionality such as a back button, take a look at this answer. You need to use UINavigationBar pushNavigationItem.

    using UINavigationBar without UINavigationController

    In your example, you are misusing the items property. The documentation for UINavigationBar states,

    The bottom item is at index 0, the back item is at index n-2, 
    and the top item is at index n-1, where n is the number of items in the array.
    

    In order to do accomplish what you're trying to do with a UINavigationBar, I think you need multiple navigationItems.

    It would be MUCH easier to either use a UIToolbar or use the UINavigationBar in conjunction with a UINavigationController.

    Edit Now that you posted the image, I think the reason you can't see the right bar button is because your frame width is too large. The iphone screen is 320 px wide, so your frame for the navigationBar should be CGRectMake(0, 0, 320, 44)