How to add a toolbar to an iOS iPhone app with a Storyboard

I’ve been playing around with iPhone apps a little bit.

Some apps require a toolbar in iPhones apps.

A basic task is to add a toolbar with buttons to your application using XCode.

Lots of samples online are using old versions of XCode. Allow me to demonstrate how to add a toolbar to an app with Storyboards.

Create a new Project

In Xcode, File -> New Project. Choose Single View Application. I named my application com.myapps.toolbars.

Add a toolbar

If you can’t see it, choose View -> Navigators -> Show Project Navigator.

If you can’t see it, choose View -> Utilities -> Show Object Library.

Open the MainStoryboard_iPhone.storyboard. Click on the View.

In the Object Library (which should be in a window at the bottom right of your screen), scroll to the bottom and choose Toolbar. Drag it onto the View. Your screen should look like this:

Wire up the button

Now we need to add some code which will be fired when the button is clicked.

Open ViewController.m. At the end of the file, before the last @end, paste the following:

-(IBAction) buttonClicked
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hello world"
message:@"You clicked the button"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
}

This is the code which will execute when the button is clicked, and it will display a simple Hello World popup.

Our final step is to wire up the button to this method. To make this easier we can use the Assistant Editor.

In Xcode, go View -> Assistant Editors on Right. Then View -> Show Assistant Editor.

If your screen is small, you might want to go View -> Utilities -> Hide Utilities.

The Assistant Editor should have ViewController.h open. In the Assistant Editor toolbar at the top, it should say Automatic > ViewController.h > No Selection. In that toolbar, click on ViewController.h and choose ViewController.m from the dropdown.

In the main window, click on the toolbar we added to our View, then on our “Item” toolbar button. Now right click it to bring up the “Bar Button Item – Item” menu.
Under Sent Actions, next to selector there is a + button. Click that and then drag it to the buttonClicked method in ViewController.m.

Hooray! Now our toolbar button is wired up to the method. Let’s run our app to test it.

In XCode’s toolbar, next to the big Run and Stop button you should see a drop down. Choose iPhone Simulator, then click the Run button.


Discover more from mycodetips

Subscribe to get the latest posts sent to your email.

Discover more from mycodetips

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top