Storyboard Tutorial: Create Tab Bar Controller and Web View

52 Flares 52 Flares ×

This is the third article of the Storyboards series. Last time, we discussed how to pass data between view controllers with segue. It should be easy, right? Now let’s continue to polish our Storyboard project and see how you can create to two other common UI elements in iPhone apps.

In this tutorial, you’ll learn:

  • How to Create a Tab Bar Controller
  • How to Create an About page using UIWebView

If you’re new to Storyboards, I suggest you to check out the first tutorial. All the materials discussed in this material are based on the work we’ve done before.

Tab Bar Controller and UIWebView

First, as usual, let’s have a brief introduction for Tab Bar Controller and UIWebView. You may not be familiar with the term “Tab Bar” but it’s commonly found in most of the iPhone apps. Just take a look at the below sample apps. All of them make use of the Tab Bar controller to display distinct view in each tab. Normally the Tab Bar contains at least two tabs and you’re allowed to add up to five tabs depending on your needs.

Sample App with Tab Bar Interface

Sample App with Tab Bar Interface

UIWebView, on the other hand, is a handy component to load web content. In some cases, you want to display a single web page locally in your app or let users access external web pages within your app. You can simply embed the UIWebView object in your app and send it a request to load the web content.

Creating a Tab Bar Controller

Now back to our Xcode project. Let me first recap what we’ve done. If you’ve followed the previous tutorial, you should build a simple recipe app with Navigation interface. It’s not completely implemented but just works.

Recipe App With Correct Detail View

Final Deliverable in Previous Tutorial

In this tutorial, we’re going to polish the app and create a tab bar interface. You may think it’ll be difficult and requires a lot of coding. The introduction of Storyboarding feature simplifies everything. It’s so easy to embed the navigation controller into a tab bar controller with just point and click.

First, select the “Navigation Controller” in MainStoryboard.storyboard. Then select “Editor” in the menu and choose “Embed in”, followed by “Tab Bar Controller”.

Storyboard Embed Tab Bar Controller

Embed Navigation Controller in Tab Bar Controller

As you can see from below figure, Xcode automatically puts the navigation controller inside a tab bar controller. Super easy, right? You may think that’s trivial. Before Apple introduced the Storyboarding feature, you would need to write code and design a separate NIB in order to embed a navigation controller.

Storyboards Tab Bar Controller Added

Navigation Controller is embedded in Tab Bar Controller

Changing Tab Bar Item Name

By default, the tab bar item is not named and without an icon. Select the tab item in Navigation Controller. You’re free to change the name and specify an icon in the Attributes Inspector. The tab bar item is default to the “custom” identifier. When it’s set to custom, that means you have to specify the title and image manually.

Storyboard Tab Bar Item

Customize Tab Bar Item

You can also use some built-in tab bar items (e.g. More, Favorites, Top Rated) that already include an icon. Let’s keep the tutorial simple and utilize the built-in item. Select “Featured” for the identifier and your screen should look like this:

Storyboard Featured Tab Bar Item

Change Tab Bar Item to Featured

Run Your App

It’s now ready to test the app. Hit the Run button and see how it looks. The app should be very similar the one we built in the previous tutorial but with the tab bar.

Recipe App with Tab Bar

Adding a New Tab

You use tab bar interface to organize your app into distinct modes of operation. Each tab delivers specific functions. Obviously, there are at least two tabs in an app when tab bar controller is used. So we’re going to create a new tab for displaying the app’s “About” page.

Drag a “Navigation Controller” object into the Storyboard. The default navigation controller is associated with a table view controller. Just leave it as is. We’ll change it later.

Tab Bar New Navigation Controller

Add a New Navigation Controller

Next, we have to establish a relationship between the new navigation controller and the existing tab bar controller. Press and hold the “control” key, click the Tab Bar Controller and drag the pointer to the new Navigation Controller.

Tab Bar Controller Links Navigation Controller

Link Up Tab Bar Controller and Navigation Controller

Release both buttons and a pop-up is displayed. Select the “Relationship – View Controllers” option. This tells Xcode that the new Navigation Controller is a part of Tab Bar Controller.

Tab Bar Controller Relationship Prompt

Establish Relationship with Navigation Controller

As soon as the relationship is established, the Tab Bar Controller automatically adds a new tab and associates it with the new Navigation Controller.

Tab Bar Controller with New Unamed Tab

Tab Bar Controller with New Tab

Change the tab bar item of the new Navigation Controller to “More”. Save the Storyboard and run the app again. Don’t you see the new “More” tab?

Recipe App with Two Tabs

Creating the ‘About’ Page with UIWebView

The “More” tab is now empty. We’re going to turn it into a web view for displaying the “About” page of the app. First, delete the “Table View Controller” and replace it with a View Controller. Simply select the “Table View Controller” and click DELETE button to remove it. Then drag the “View Controller” object from Object Library.

Storyboard Blank View Controller

Replace Table View Controller with View Controller

As of now, the blank View Controller is not associated with the Navigation Controller. We have to link them up. Press and hold the command key, select the Navigation Controller and drag it towards the View Controller.

Storyboard link View Controller

Link up View Controller and Navigation Controller

Like what we’ve done earlier, select the “Relationship – View Controllers” option to establish the relationship between both controllers.

Storyboard View Controller Relationship

Associated the Relationship Between View Controllers

The main purpose of this view controller is to render the “About” web page. iOS SDK has a built-in UIWebView object to display web content. You can simply embed the UIWebView object in any view controller. Later you send it a HTTP request and it automatically loads the web content for you. Locate the “Web View” in Object Library and add it into the View Controller.

View Controller UIWebView

Add Web View into View Controller

Assigning a New View Controller Class

As explained in previous tutorial, a blank view controller is assigned with the default UIViewController class, that only provides the fundamental view management model. Apparently, it doesn’t come with a variable for controlling the UIWebView. Yet we have to create a new View Controller class that extends from the UIViewController.

In the Project Navigator, right-click the “RecipeBook” folder and select “New File…”.

Storyboard New View Controller

Create New File in Xcode Project

Choose “Objective-C Class” under Cocoa Touch as the class template.

Storyboard New ObjectiveC Class

Select Objective C Class

Name the class as “AboutViewController” and it’s a subclass of “UIViewController”. Make sure you uncheck the option of “With XIB for user interface”. As we’re using Storyboards for designing the user interface, we do not need to create a separate interface builder file. Click “Next” and save the file in your project folder.

New Class AboutViewController

Create a new class - AboutViewController

Next, assign the view controller with the “AboutViewController”. Go back to the Storyboards editor and select the view controller. In the identity inspector, change the class to “AboutViewController”.

View Controller with AboutViewController

Set the Custom Class to AboutViewController

Use UIWebView to Load a Request

To request UIWebView to load web content, we have to write a few lines of code. In brief, there are three things we need to implement:

  • Add the “about.html” and “about.jpg” to your Xcode project
  • Assign a variable for UIWebView and associate it with the Web View object in Storyboard
  • Use the loadRequest: method in UIWebView to load web content

Adding ‘About.html’

The UIWebView class allows you to load web content both locally and remotely. You can send it a HTTP request (e.g. http://www.google.com) to load a remote website. Alternatively, you can tell UIWebView to load web pages embed in your app. For this tutorial, we’ll put the “about.html” inside our app.

You can create your own about.html. For your convenience, however, download the about.zip, extract it and add all the files into the Xcode project.

Assign a Variable for UIWebView

Select the “AboutViewController.h” and add a new property for UIWebView:

1
2
3
4
5
@interface AboutViewController : UIViewController

@property (nonatomic, strong) IBOutlet UIWebView *webView;

@end

Go to the “AboutViewController.m” and add the synthesis for the variable. Make sure you place the code under “@implementation AboutViewController”:

1
2
3
@implementation AboutViewController

@synthesize webView;
If you’ve forgotten what the interface and implementation are, go back to this tutorial and revisit the concept.

As usual, it’s required to establish connection between the “webView” variable and the visual web view. In the Storyboards editor, press & hold the command key and then click the “View Controller” icon, drag it to the Web View object. Release both buttons and a pop-up shows variables for your selection. Choose the “webView” variable.

Link Up UIWebView and webView

Link Up UIWebView and webView Variable

Load Web Content

Inside viewDidLoad method, add the following code to load the “about.html”:

1
2
3
4
5
6
7
8
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Add code to load web content in UIWebView
    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"about.html" ofType:nil]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [webView loadRequest:request];
}

The UIWebView class provides a convenient method named “loadRequest:” to load web content. What you need to do is to pass it a URL request. Line 5 of the above code returns the system path of the “about.html” in the form of NSURL object. Line 6 creates a NSURLRequest using the URL. Obviously, line 7 sends the request to web view.

Final Deliverable

Hit the Run button and try out the app. If you got everything correctly, your final deliverable should look like below. When you select the “More” tab, it automatically loads the “about.html”.

Recipe App with Two Tabs

Summary

Storyboarding has streamlined the user interface design of iOS app. As you can see from this tutorial, without a single line of code, you can create a tab bar controller and embed other controllers in the tab items. We’ve also showed you how to use UIWebView to load web content. UIWebView offers basic function of a mobile browser. Whenever you need to display web page within your app, embed the web view and send it a request.

In the upcoming tutorials, we’ll continue to explore other new features of Storyboards. Stay tuned and make sure you leave us comment below if you have any questions.

Update: You can now download the full source code for your reference.

You May Like These:

Get Free Chapters of Our AppCoda Book

Learn iOS 7 Programming from Scratch

The Learn iOS 7 Programming from Scratch is a 400-page eBook written for beginners with little or even no programming experience. It is based on the tutorials of our popular programming course. The book starts with the basics and walks you through the process to create iOS apps using iOS 7 SDK and Xcode 5. Want to learn more? Check it out here and get two free chapters.


Build Your Own Game and Monetize on the Side

Learn how to develop your first iOS game and make money on the side. The starter kit will come with full source code of a memory game for both iPhone and iPad, as well as, a complete guide to explain how the code works. Check out the starter kit to learn more.


About Simon Ng

Founder of AppCoda. Author of Learn iOS 7 Programming from Scratch. iOS App Developer and Blogger. Follow me at Facebook, Twitter and Google+.

  • http://twitter.com/geztogether gezt

    nice tutorial, will try this :D, thnx

  • Jake

    great tutorial :D
    i love all your tutorials

  • Pingback: Top iPad Stories (June 25 – June 30) | Total iPad

  • Tekle

    Wow! This is great!

    Thanks!

  • sanz

    I have been following your tutorials and these tutorial are the best than others i tried

  • Toby powell

    Your tutorials are the best I’ve read! And I’ve read many, every tutorial is like gold! Keep up the great work

    • http://www.simonblog.com Simon Ng

      Thanks, Toby! Great to hear that.

  • samsulfreude

    Wow, today i successfully learned UIWebView, THANKS TO YOU! :D
    Gratitude, my friend! :)

  • Miti

    Why can’t I subscribe? No message comes to my inbox:(

  • 4ki

    That’s great tutorials. I want to develop push notification for iOS WebBroswer app using UIWebView. My plan is to push notification from Desktop web browser to iOS WebBrower. Do you have any tutorials to do that? Thanks in advance!

  • jacovoxdot.com

    i just want to say thank you,,, really, i’ve been looking a way to put multiple urls on different views and your post is the only useful on internet right now,, i am not kidding.

    thanks again

    • http://www.simonblog.com Simon Ng

      Great to hear that! Thanks. :-)

  • trice

    Great tutorials! In the storyboard view, you mention connecting some of the controllers, views, variables, etc. by selecting the item then holding down the command key and dragging to the other item. That didn’t work for me…but holding down the control key worked instead. Maybe xcode changed a shortcut key on me?

  • Pingback: 第十二部分:Storyboard教程-创建Tab Bar控制器和Web视图 (2) | EntLib.net 技术分享平台

  • BRIAN LAURA

    Aloha,
    I really enjoyed this tutorial, but I am having trouble going back to the previous view— webview, I was thinking a back button might work. Once I am on the webview page — html page, I press a button which loads a image then I am stuck on that image-page. I can’t go back to the previous webview page — html page, after pressing a button that loads an image. How do you solve this problem? Thanks for all your help.

    Sincerely,
    Brian Laura

  • Natarajan

    Hi

    When i run this code.. i get the below error under main.m

    int main(int argc, char *argv[])
    {
    @autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([RecipeBookAppDelegate class]));
    }
    }

    • Natarajan

      the run time error is Thread 1: EXC_BREAKPOINT(code=EXC_I386_BPT,sub code=0*0)

      • Tim

        I just had the something, read through the error output box, and found out it’s looking for a UITableViewController … eventho, there’s no UITableViewController for the about page. In order to fix this, delete the two AboutDetailViewController files (h/m). go back to the step where you had to the AboutDetailViewController .. and ENSURE your subclass dropdown menu is selected as UIViewController, instead of UITableViewController = ) Good luck. mine works now

        • http://twitter.com/nat4ancorp Nat4an

          I tried this trick out and it didn’t work for me. :( But however, I was able to find out another way to do this. I think it might be simplier:

          instead of:

          NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@”yourfileorurl” ofType:nil]];

          use this:

          NSURL *url = [NSURL URLWithString:@"http://yourpathorwebfile"];

          This is because what this tutorial is intended to do it load a resource file from the project resources and the reason for getting the above error is because we are trying to load a remote webpage into the UIWebView instead of a local resource file. Hope this helps. I know it did for me and I stood up and looked accomplished when i figured this out. :)

  • Alex

    Finally a Tutorial that is easy to follow and makes me understand Xcode! Please write more.. it’s so much better than the youtube tutorials. Please keep it up.

  • ravi

    Tutorial is awesome..But u forgot to show how to display the lable

  • Pingback: IOS编程教程(十三):如何往表视图(Table View)添加搜索栏(Search Bar) | 编程·早晨

  • Pingback: IOS编程教程(十四):回到基础,介绍面向对象编程 | 编程·早晨

  • Eduardo Jose Christofoletti

    Nice tutorial and easy to learn nice work bro! congrats from Brazil … :)

    • http://www.simonblog.com Simon Ng

      Thanks! More tutorials to come. Stay tuned :-)

  • Hugh Jeremy

    Thats brilliant, I would really appreciate it if you could add a quick note on how to make the web view load when the view is not on the tab bar currently displaying, so when you go on the web view tab it has already loaded :) I assume it would be in the appDelegate? Thanks for all the helpful tutorials!

  • http://www.facebook.com/Ebirulz Okpongu Ebirulz

    Great tutorial…… Thanks a lot.

  • Vikas

    Such a nice tutorials
    thank’s

  • http://www.facebook.com/people/Bharath-Rajakumar/1195670908 Bharath Rajakumar

    Thank you so much… This is gonna helpful for my Software Engineering Project :)

  • tcm692

    When attempting to connect the “View Controller” icon & dragging it to the Web View object, I cannot choose the “webView” variable, I only see “view”. I think on the previous step when attempting to rename the view controller (in the identity inspector, change the class to “AboutViewController” for the UIWebView), it does not seem to work. While I can type in ‘AboutViewController’ it does not save.

    Any help would be greatly appreciated!!

    • http://www.facebook.com/paulpaulpaul05 Paul Paul

      I had that problem too, but I’ve solved it by erasing the current About view controller, and replace it with a new one; Also do not forget to follow the same steps again; Hope it works for you

  • tcm692

    How you you sort placement of tabs when you have multiple tabs? As you add new navigation controllers to the tab bar controller, it puts the new tabs as next in line. For example, if I’ve made tabs 1 (i.e. main) & 2 (help) and then I need to add a 3rd tab, but it makes more sense to be seen before the #2 (help) tab, how do I tell the tab bar controller that?

    • tcm692

      Never mind – I found it…you can drag & drop within the tab bar controller. I had to restart Xcode, but that did it.

  • shailesh

    Nice tutorial

  • aamir khan

    best tutorials

  • HLA

    Thanks a lot…..bro

  • Pingback: Custom Tab Bar | iCodeCenter

  • Pingback: IOS编程教程(十三):如何往表视图(Table View)添加搜索栏(Search Bar) - iOS - 开发者第662196个问答

  • Jon G

    I’m having an issue I hope you can help with. Everytime I try to run your code I get this error:

    Terminating app due to uncaught exception ‘NSInvalidArgumentException’, reason: ‘*** -[NSURL initFileURLWithPath:]: nil string parameter’

    The code is this:

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@”ImportClearance.html” ofType:nil]];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    [webView loadRequest:request];

    And it immediately crashed on the first line. What am I missing here?

    Love the site it has been very helpful to me as a total newbie!

  • http://www.arttrav.com arttrav

    Thanks very much, this was just what we needed to build our simple app!

  • Kim

    YES! Just what i needed!
    Now back to my project :-)

    Thanks for GREAT tut`s!!!! :) :) :)

  • CEMSOFT SOFTWARE

    I really enjoyed this tutorial,go on appcoda , thanks.

  • NJ

    Thank You :)

  • sam

    What in case if I want to make my tab bar customized? I mean in .xib, we generally subclass the UITabbarController but I didn’t get any way to do this via this magical tool (StoryBoards).

  • Miguel Cardoso

    Great job with all the tutorials!!
    I’m really learning.

    All so clean and understable.

    Thanks man!

  • Pingback: Ios 7 with xcode 5 training | Iphone Tutorial Point

52 Flares Twitter 6 Facebook 30 Google+ 15 LinkedIn 1 52 Flares ×