Monday, May 18, 2009

Creating a UITabBarController application


This example describes the steps required to create an iPhone application using a UITabBarController. The UITabBarController will handle the switching between different views in your application.

Step 1: Create the new Project

Launch XCode and create a new 'Window-based application'.


Save the new project as TabBar.

Step 2: Add the tab bar controller

In the project Window, expand the 'Resources' folder and open the 'MainWindow.xib' by double clicking on it.


When Interface Builder opens up, open up the Library (Under the Tools menu,) and drag a UITabBarController from the library into the MainWindow application.

Save the 'MainWindow.xib' file.

Step 3: Create new Views

When the controller is added, a window will pop up with a title of 'Tab bar Controller' and a two tabs along the bottom. Clicking on the tabs will switch between the two view placeholders. On the first tab 'Item 1', drag a view from the library and place it on the placeholder above the tabs. The view should meld into place. Next, drag a label from the library and place it in the new view. Double click on the label and change the text to '1st Tab' to ensure that we know which tab is which.


Next we repeat the same process for the second tab. Click on the 2nd tab, drag a view from the library onto the placeholder, add a label and change the text this time to be '2nd Tab'.

Step 4: Update the delegate to load the view (.h and .m)

Switch back to XCode and edit the TabBarAppDelegate.h header file. In this we need to define a property for the tabBarController.


Now that we have defined the property, we need to load the view from the controller. In the TabBarDelegate.m we need to do three things:
  1. synthesize the new property.
  2. In method add the tabBarControllers view to the window.
  3. release the resource.

That is all the code that is required.

Step 5: Link it all together!

The last step in the process is to link it all together. In summary we have done two things that are related.

In the XIB file we added a new UITabBarController to the UI and put some custom views on it.

In the source files we created a new property of type UITabBarController and told the application to load the view from it when the app finishes launching.

To link both of these together we need to go back to the Interface Builder and create the link. In the MainWindow application, select the Tab Bar App Delegate and open up the 'Connections Inspector' from the 'Tools' menu. In the Outlets section of this window you should see an entry for the tabBarController that we defined earlier in the source file. This outlet needs to be linked to the Tab bar Controller in our XIB. To do this, hold down the Ctrl key and drag the circle to the Tab Bar Controller window.

Now that this is done, in XCode you can 'Build and Go' to see you application in the simulator.