Tag Archives: UIBarButton

How to create multiple buttons in a UINavigationBar

Screen Shot 2014-05-17 at 09.54.04Sometimes a single button left and right is just not enough for complex apps. Especially on the iPad we have this large space in the navigation bar. But Interface Builder only allows us to add one button on the left and one on the right.

How do we add more buttons to those spaces? Code is the answer.

Both the left and the right space of a UINavigationBar can take an array of barButtonItems which we can populate with as many buttons as space will allow.

In this example I’m using the Master/Detail template to create an array in the viewDidLoad method of the DetailViewController. This will create the effect shown in the screenshot:

Note how you can create fixed spaces between the buttons as shown.

You can also space those buttons evenly across the whole bar by using the UIBarButtonSystemItemFlexibleSpace, in which case there’s no need to pass the width parameter. When you do, the buttons will be spaced between the right side of the bar and the title if there is one, or across the whole bar if the title is empty.

How to hide a UIBarButtonItem in your Navigation Controller

Since UIBarButtonItems do not have a “hidden” property, we can’t just set this to yes and it’ll disappear. Instead, we can set them to nil.

In this example we’re hiding the right item in the navigation controller:

How to create a UIBarButtonItem in code and make it call a method

Some things are really easy to do via a Storyboard – but when you want to create the same thing in code I frequently forget how to do it.

Turns out it’s equally simple: this example assumes you have a View Controller which is embedded in a Navigation Controller (so it already has a UINavigationBar at the top). Here’s how you add a button to it, set the title and target, and tell it what to do when it’s pressed:

You can set the button on the left hand site by using self.navigationItem.leftBarButtonItem