iPhone SDK Articles

Saturday, July 5, 2008

Tab Bar Controller Tutorial


In this tutorial, you will learn how to create applications with a Tab Bar Controller. Tab Bar Controllers can be seen in iPhone/iPod Touch applications like the Clock.In this tutorial, you will learn how to create applications with a Tab Bar Controller. Tab Bar Controllers can be seen in iPhone/iPod Touch applications like the Clock.

In this tutorial, you will learn to
  1. Create a Tab Bar Controller
  2. Adding a view
  3. Adding the Tab Bar Controller to the Window
Create a Tab Bar Controller
Create a new project by selecting Window-Based Application. Open the Interface Builder by double clicking the MainWindow.xib file and add a Tab Bar Controller from the Library. What you see is a Tab Bar Controller with two Bar Items created for us.

A Tab Bar Item acts as a button by which we switch among different views. As we can see a Tab Bar Item can have a title and a image associated to it. Double click Item 1 and in the attributes builder we can set the title and image for the tab bar item.

To add a image to the project is very simple, select Xcode and click on Project -> Add to Project and select a image. You will see that the image is seen in Xcode.

Organizing Files
It is however not a good practice to store files anywhere. To overcome this problem we can either add a folder to the project or simple create a group to store our images. Create a group does not create a folder in the file system but creates a logical view in Xcode.

Note: This tutorial will not be setting any images to the Tab Bar Items.

Adding View to the Tab Bar Controller.
Adding a view is very simple, drag and drop the view from the library to the place holder where it says View (above the tab bar items). You can add another view by clicking View Two Tab Bar Item.

Select View One and add a text field and a label. Select the text field and set its placeholder to say "Enter Name", Type is Name Phone Pad and Return Key as Done. Make sure that "Clear Context Before Drawing" is checked for the text field and the label.

Select View Two and add a label and change its text to View Two.

Adding the Tab Bar Controller to the Window.
Now all we have to do is add the tab bar controller to the window. To do this, we need to create a connection from the tab bar controller to the Tab Bar Controller App Delegate. Create an instance variable of type UITabBarController and mark it with IBOutlet so it shows up in the Interface Builder.

In the applicationDidFinishLaunching method, we need to add the tab bar controller as a sub view to the existing window. Your method should look like the following below.

Now open Interface Builder and Select Tab Bar Controller App Delegate and open the connections inspector. Create a connection from the tabBarController variable to the Tab Bar Controller. In Xcode click on Build and Go to see the application running. Clicking on View One and View Two will change the view, notice that we did not have to write this functionality but the Tab Bar Controller makes it possible.

In most iPhone application there is no done/save button and we still need to close the text editor when the user is done typing.

To do this we need to create a connection between the controls defined on view one and the objects created in our application delegate.

To learn how to create connections between the controls and the objects, read about it in my First iPhone Tutorial.

Since we declared our instance variables/properties in the delegate file, the objects in the Interface Builder will be present in the TabBarController App Delegate file and not in the File's Owner proxy object. Create appropriate connections and also make a connection from the text field delegate to the TabBarControllerTutorial App Delegate. Implement the textFieldShouldReturn method and one line in there to update the label.

Now you know how to create an application with a TabBarController. Click here to download the source code. Please don't forget to leave a comment.

My next tutorial will show you how to use the Navigation Controller.

35 comments:

Jason said...

You cannot follow this tutorial directly. You do not specify everything that must be done. In particular the TabBarAppliationDelegate is missing some of the outlets it has in the source files you posted.

With that said, it was still a helpful tutorial.

Rogger said...

Thanks for this tutorial! A tutorial about using the accelerometer would be nice.

jai said...

Hi Jason,

Sorry to hear you had some problems following the tutorial. I will try to be more descriptive.

Jai

jai said...

Hi Roger,

Thank you for your time. I will try to come up with an accelerometer tutorial soon.

Jai

Anonymous said...

for those of you following along with this article.. you'll need to load up Interface builder then click on the Tab Bar Controller Delegate (or whatever you called your application when created). Go to the connections tab then drag the Tab Bar Controller outlet to the tab bar controller at the bottom of the view to make the connection. Once that is done your app can build and run. If you dont do this you'll see nothing but a white screen.

To JAI, as others have said.. thanks for posting these articles.. good stuff. just make sure you dot your I's and cross your T's as you dont want to confuse others who are new to the Obj-c and x-code. In addition, just so there's no confusion make sure you specify in your tutorial the name of the project so readers know what to expect.

Thanks,
John

Fabian said...

Nice Tutorial.
Is their a way that i can execute some code every time i change the tab?

chiranjeevi said...

i really liked your tutorials.Very good place to start if you are a new iphone developer.
Very Helpful...Please post more.

Manuel said...

Hm… I'm not getting this part:
«You can add another view by clicking View Two Tab Bar Item.»
What do I have to do between adding the tab bar and adding a view? It all just is becomes the same view…

Thanks a lot! And thanks very much for the tutorials!

Anonymous said...

UITableView seems only handle single columns, any one can advice how to display multiple columns table?
JT

Anonymous said...

Hi. While the tutorial wasn't perfectly clear, I enjoyed that about it. It helped me figure somethings out on my own.

Thanks.

Anonymous said...

I want to use the navigation control come with the tabbar. However, after I set it in IB, it doesn't show up on the application.

This is how I did it:
- set the tabbarController property "Top Bar" to "Navigation Bar" in IB
- drag a navigation item to the Bar location

Anonymous said...

I want to use the navigation control come with the tabbar. However, after I set it in IB, it doesn't show up on the application.

This is how I did it:
- set the tabbarController property "Top Bar" to "Navigation Bar" in IB
- drag a navigation item to the Bar location

Anonymous said...

Please help me,how can we use two views at same tab.
For eg, I have two UIView say view1 and view2 both having a button and a label.So how can i toogle between these two views in the same tab.

Lethal looks said...

hey..
can u please also tell us how to add the tab-bar to the window in another view and not the app delegate (ie if we want to start showing the tab bar from say the 4th view)

jai said...

Hello,

To lethal looks

Why can't you add the tab bar in the 4th view directly, so it will not show up on the first, second and the third view.

You can send me an email at iphonearticles [@] gmail [.] com, if I do not understand your question.

Thanks,
iPhone SDK Articles

Dairen said...

Thank you very much for putting this together. I am new to this type of programming so although many steps were omitted that would be helpful to a beginner, providing the sample code was extremely helpful and allowed me to obtain the information I needed to complete a similar project. Thanks again!

bones237 said...

Excellent work on all the tutorials you have done. I have referenced them alot in my developement.
One ques. tho:
I'm trying to use the tab bar controller like you demonstrated with only the "...AppDelegate" files. In one of my views, i'm trying to us the 'touchesBegan' method so the keyboard will disappear when user touches outside the text field. I've used this method before with success but that was a different app where i used a view controller. It comes up with a warning: "NSObject may not respond to 'touchesBegan'...........no matching signature..." Do u know why??

Usman Ismail said...

I find that making the UI programatically is much more convenient here is a tutorial on how to do so.

http://knol.google.com/k/usman-ismail/iphone-sdk-tabbars

Khagesh said...

Nice tutorial ...
Please post more for other component.

-Khagesh

jai said...

To bones237

may I know where are you writing the touches began code, in which view controller or are you doing this in the application delegate, which may not work I think because it is not really tied to any view.

Happy Programming,
iPhone SDK Articles

Anonymous said...

I've followed the tutorial to the end, but I'm at a loss to see how to to get the "Done" gadget on the virtual keyboard to remove the 'board from display.

From the first tutorial, it appears that the way to do this is to implement the UITextFieldDelegate protocol - but I can't get this to work :(

As a general comment (from someone new to Objective C programming) it would be useful to explain in more detail why certain things are being done, in addition to how to do them...

Will said...

I think I have the same question as @LethalLooks upstream. If I want the tab bar control on a view that is not the first window of my application, how do I add it?

Anonymous said...

Thank you. Thank you. Thank you. I've been struggling, in particular, with how to link the window in interface builder to the [insert type of] controller. I Didn't realize that it would take some code in the app delegate, and you've cleared that up. Thanks for sharing. :)

Justus said...

Thank you very much for your tutorials!

Reading all the stuff Apple provides is interesting but not really instructive. All the time I read their docs I felt the urge to write my own little Hello World app. ;)

Justus

Anonymous said...

This is a great tutorial, thanks!

I particularly liked the final challenge of working out how to implement the textFieldShouldReturn method. Or more specifically I liked the satisfaction of working it out haha.

Sam Dutton said...

Thanks again for all the effort you've put into these tutorials.

However, I also agree with the poster who suggested you should take care to 'dot your Is and cross your Ts'! Some tutorial steps are missing and (in the first tutorial at least) some of your screenshot code is wrong.

It might also be useful to have links directly to code for the interface and implementation files as well as (or rather than) a link to the whole project.

Some specific comments below.

Sam

...........................

- 'Double click Item 1 and in the attributes builder' should be 'Double click Item 1 and from the Interface Builder Tools menu, select Attributes Inspector ...'

- 'Adding a view is very simple, drag and drop the view from the library to the place holder where it says View (above the tab bar items). You can add another view by clicking View Two Tab Bar Item.' I think this is a bit unclear: maybe 'Open the Library window and drag a View item from the Windows, Views & Bars section to the View area above the two tab bar items in the Tab Bar Controller window.'

- I think the comments about images on tab bar items could be reduced to one sentence -- it's a bit confusing here.

- In the 'Adding the Tab Bar Controller to the Window' section, it isn't clear which file you're referring to, since you haven't specified a name for the project. I think you need to be more specific about how to make the connection between the app delegate and the controller.

- In order to complete the last part of the tutorial, you need to explain to add the following code to the app delegate interface:
IBOutlet UITextField *txtInput;
IBOutlet UILabel *lblMessage;
...and the properties:
@property (nonatomic, retain) IBOutlet UITextField *txtInput;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;
...and dealloc:
[txtInput release];
[lblMessage release];

- theTextFied in your source code should probably be theTextField

- the connections steps required to change the label text aren't clear, even if you look back at your first iPhone tutorial

eduardo said...

Nice tutorial for beginners.

Anonymous said...

The last block of code fixed my errors, but I still have plenty of warnings and all I get is a black screen in the simulator.

Anonymous said...

BTW ... Wouldn't it be simpler to just use the New Project - Tab Bar Application?

iPhone SDK Articles said...

I think you are absolutely right, creating a project by selecting "Tab Bar Application" template would be easy and painless without the extra effort.

Happy Programming,
iPhone SDK Articles

iPhone SDK Articles said...

Would it possible for you to send me your source code so I can take a closer look at what is going on?

Happy Programming,
iPhone SDK Articles

Anonymous said...

Thanks, it was a good tutorial, but as mentioned, several steps were either omitted, or not explained such that a nubie could follow... such things as mentioning which file to add which code to. Downloading your sample code solved most things... I could compare my source files with yours to see where you added things.

The connections were the most confusing thing, especially for someone who hadn't taken any of your other tutorials. I figured out what to do by dumb luck!

For anyone still struggling after all the great comments above, I'll add the things that helped me to get it working. The *sections reference the sections in the tutorial.

*Adding View to the Tab Bar Controller:

In the library, scroll down until you see the section headed "Windows, Views & Bars" and drag the View from there and drop it on the placeholder in the interface window. Do not confuse this library item with View Controller near the top of the list, or any of the Data Views.

For each label, change its color from white to black so you'll be able to see it against the white background of the View.


*Adding the Tab Bar Controller to the Window

Where you see below "MyAppName", replace that text with the name of your own application.

Open the MyAppNameAppDelegate.h file and add the following line:

@class MyAppNameViewController;

In the section that begins @interface MyAppNameAppDelegate :

Replace what is there with the following:

IBOutlet UIWindow *window;
IBOutlet UITabBarController *tabBarController;
IBOutlet UITextField *txtInput;
IBOutlet UILabel *lblMessage;

In the section starting with @property replace what is there with the following:

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UITabBarController *tabBarController;
@property (nonatomic, retain) IBOutlet UITextField *txtInput;
@property (nonatomic, retain) IBOutlet UILabel *lblMessage;

By defining these properties, you will be able to draw connections between these variables and the items you have added to the screen.

Now, to connect the Tab Bar Controller to your MyAppNameAppDelegate, double-click your MainWindow.xib in the project to launch the Interface Builder (if it is not already open). Highlight the Tab Bar Controller icon in the group window that contains File's Owner, First Responder, My App Name App Delegate, Window and Tab Bar Controller.

If the Attribute Inspector is not visible, go to the Tools menu and select Attribute Inspector. Click on the second tab which has a blue icon with arrow, the title bar should read Tab Bar Controller Connections.

In the Referencing Objects section, you should see tabBarController, click the mouse in the blank circle and drag down into the group window and drop it on the icon for My App Name App Delegate. You should see a blue line draw on the screen as you are dragging. When finished, you should see that in the Tab Bar Controller Connections, My App Name App Delegate has been added next to tabBarController with a connecting line between them.

Now, highlight the icon for My App Name App Delegate in the group window and look at the connections for this object. In the Outlets section click in the blank circle next to the variable tabBarController and drag down to the Tab Bar Controller control visible in your interface window. As you drag over items in the interface, their names will be visible, make sure you drop on the control that says Tab Bar Controller.

Likewise, drag from lblMessage to the label on the first view, and from the variable txtInput to the textbox on the first view.

In the Referencing Outlets section, you should already see a connection between delegate and File's Owner with a dark circle next to it. Click on the dark circle and drag down to the textbox on the first view. Now, the Referencing Outlets section should show that delegate connects to "Multiple", and if you expand "Multiple" you will see File's Owner and the Textbox listed.

Open the file MyAppNameAppDelegate.m in the editor. Replace the line beginning with @synthesize window; to:

@synthesize window, tabBarController, txtInput, lblMessage;

Add the following code to the applicationDidFinishLaunching method, above the comment to // Override point

// Add the tab bar controller as a sub view to the window.
[window addSubview:[tabBarController view]];

Add the following to the dealloc method to deallocate all of the controls

- (void)dealloc {

[lblMessage release];
[txtInput release];
[tabBarController release];
[window release];
[super dealloc];
}

Above the dealloc method, add the following method to close the keyboard and update the label with the text that you typed.

- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {

if(txtInput == theTextField)
{
[txtInput resignFirstResponder];
}

//Update the label.
lblMessage.text = txtInput.text;

return YES;
}

JES said...

This is all great stuff. One thing missing from all of this is something about the tab bar icons. Here are a couple posts describing how to create them yourself:

http://osmorphis.blogspot.com/2009/02/tab-bar-icons-part-1_4115.html
http://osmorphis.blogspot.com/2009/03/tab-bar-icons-part-2.html

Michael Curylo said...

I am trying to make the tab bar disappear in certain views. I am using it most of the time, but for example, ... i have an "info" button, that i flip the view to and I want the tab bars to disappear and just have a "done" button.

any ideas on how to override it?
the iPod player in the iPhone does it!

iPhone SDK Articles said...

@Michael

You can try this

tabBarController.view.hidden = YES;

Hope this helps.

Happy Programming,
iPhone SDK Articles