iOS Training from beginner to advanced
Posted on July 6, 2016 by Steven Lipton
In this lesson, we’ll take a look at tab bar controllers and how to add them in the storyboard. For more on implementing them completely in code see Swift Swift: Using Tab Bar Controllers in Swift. For more on data sharing once set up in the storyboard, see Passing Data in Tab Bar controllers
Before we begin, It’s important to remember the difference between tab bar and navigation controllers. Navigation controllers are stack based, while tab controllers are parallel in execution. Think of a navigation controller as a stack of cards. You can only play the visible card. If you put a card on top of another card, only the top card is active.
Now imagine you take several cards and deal them face up. You can play any face up card. They all are active. This is a tab bar controller.
As we go through lessons on tab bar controllers, it is very important to remember this difference.
The easiest way to make a tab bar controller is through Xcode’s template. In Xcode, press Command-Shift-N or File>New>Project. Select the tabbed application.
This will give you a window with two tabs installed with two labels each and a tab item on the bottom of each controller. The template tends to make things more complicated instead of less, so it is rarely used.
The most common way to make a tab bar controller is to start from a single view and embed it in a controller. We’ll try an example of this one in Xcode. Press Command-Shift-N and select Single View. Make a file named SwiftTabBarEmbed, using Swift as the language and with a Universal device. Once created, go over to the Storyboard. Make sure the Preview setting is View as: iPhone6s(wC hR) in the lower left corner of the storyboard:
Change the color of the view controller’s background.
Select the view controller by clicking the view controller icon or title, and select Editor>Embed in>Tab Bar Controller.
This will turn the single view controller into the first view controller of the tab bar.
Add another view controller by dragging out a view controller then control-dragging from the tab bar controller to the new controller. In the pop-up, select under Relationship Segue the view controllers option.
Another segue appears on the story board.
You’ll see a second tab in the tab bar controller.
To configure the tab bar icon, go to the Item icon in the Yellow View Controller (not on the tab view controller) we just made and click it.
This will bring up in the properties inspector the Tab Bar Item and Bar Item properties. In the Tab Bar Item properties is the System Item drop down. This is where we configure the tab bar button.
In the System Item menu, Click the drop-down for System Item. you will see a list of system icons.
Select Favorites. The Icon changes both on the view controller and the tab bar controller.
Click the other view controller’s tab bar, and change the system Icon to Recents.
Click on the Preview size Button which reads iPhone 6s(wC hR). A new toolbar appears underneath it. Select the iPad 9.7″.
The view controllers in the storyboard change to iPads, so you may need to change the zoom level.
Drag out six more view controllers, so we have a total of eight controllers. Change their background colors to make then easily distinguishable.
Control-drag from the tab bar controller to each new view controller and assign Contacts, Bookmarks, Search, Downloads, and Most Viewed to the controllers, leaving one more as a custom item. The tab bar controller should look like this:
Change the Preview mode back to to an iPhone 6s. While your icons may be in a different order, you will get something like this for the tab bar at the bottom of the phone:
Compact widths, the width on most phones, cannot handle more than five tabs. If you add more than five tabs, it places a More tab as the fifth tab. What does the More tab do? Build and run as an iPhone 6s in the simulator.
Tap on the More icon in the lower right. A table appears with the missing tabs.
More gives you access to all your tabs. If you tap the tab in the table’s cell, the tab’s controller will appear. Select Downloads, and you get the downloads tab.
Tabs selected by More act slightly differently than ones in a regular tab. They are embedded in a navigation controller. You’ll see at the top a navigation bar.
The navigation bar goes back to the More table. Tap Bookmarks, and notice the navigation bar is not there, then tap More again and the Downloads controller is still there.
Select More in the navigation bar to go back to the Table view
Without any extra code, tab bar controllers let users customize their tab bars. Tap the Edit button, and you get a configuration view:
Looking closer, you’ll see that the hidden tabs are highlighted and the visible tabs are dimmed
Drag the Item tab down to the tab bar. Drop it on top of Recents. It replaces Recents.
You can also drag tabs in the tab bar to change the order. Drag Downloads on top of Contacts. Drag Downloads to the right, swapping it with Bookmarks. Your tab bar now looks like this:
I want to add two cautions to this: One of the system icons you can use is a More icon. Be careful when using the More icon in a tab bar. It can cause user confusion between the More tab and your own use for More. Make sure it is clear what you are doing.
The second caution is more insidious. When programming for tab controllers, you can get the tabs from an array. However, the order and visible tabs can change by user request with the More tab. Avoid hardwiring the tabs by their location in the array since users can change them.
Close the simulator. In the storyboard, delete the Bookmarks, Recents and Favorites view controllers (or their segues if you don’t mind the warnings) so you get a tab bar like this:
As we now have five icons, this will keep off the More icon, which requires six tabs to show up. You can reorder the tabs in the tab view controller by drag and drop. Reorder using drag and drop to this:
Click on the tab bar for the Item view controller. We can see all the tab bar properties.
The lower half has bar item properties, which directly control the title and icon for the tab. We can easily change the text. Change the Bar Item Title to Pie.
The title changes on the tab bar:
If we change a System items’s title, it becomes a custom item, and the icon disappears. Do the same to change Downloads to Pizza. Also change Contact to Square. Square, Pizza and Pie have squares for icons.
Under Title in the properties inspector, we have a drop down for Image.
For a custom bar item we can supply the icon. Image icons are not like other images. They are monochrome images, unlike anything else you have ever seen. They are set not by color but by the alpha value , or transparency of the image. You can make any image here any color, but it will show up as a solid tint color if you select an alpha value of 100% and background color if you select 0% alpha. For example I created the following icons in both high and low resolutions:
Icons are 30 points by 30 points, which means for retina images make the icon a 60 pixel by 60 pixel image and for low resolution images 30 pixel by 30 pixel. You can download them individually by right clicking the images above, and saving them to a folder. Use these file names:
You can also download a.zip file Of these here:Tab Bar Assets
For those not familiar with Apple image naming conventions, low resolution images have a file name. Retina Images have @2x appended to that file name. This tells Xcode to know what resolution it is. We have both 60×60 pixel retina and 30×30 pixel standard images. By loading both into Xcode, the system will use the correct one automatically for the device.
In Xcode’s navigator panel, open up Assets.xcassets. Select all the icon files. Drag them into the center panel in Xcode, which will highlight. Release the mouse button, and you will see a new collection in the image assets.
Return to the storyboard. On the tab we titled Square,click anywhere on the tab bar. Select the image drop-down in the tab bar properties and select the gradient bar icon.
The Gradient bar now replaces the place marker square:
Find the Pizza and Pie tab views on the storyboard, and change them the same way. The Tab bar controller now has three custom icons.
Build and run with the iPhone 6 simulator, and you will see our three icons, with Pie highlighted as selected.
As mentioned earlier, tab bar controllers make a set of single view controllers running parallel to each other. The tab bar switches the view, but the view we leave does not get dismissed, just hidden. there are two uses for such a controller. The first is a series of small independent applications related to each other. Apple’s clock app is an exmaple. The timer, alarm clock, world clock, and stopwatch all are related by a theme of time. All run independently of each other. The second use of Tab bar controllers is to use a shrared data set in different ways. Social media apps like Twitter or Instagram for example use tab bars to have different functions of displaying posts, searches, or displaying notifications that all use the same database. For this second type of use, see see Passing Data in Tab Bar controllers. We’ll look at the first type here.
Connecting a view controller in tab bars is the same as hooking up any other view controller. Make a new view controller class by pressing Command-N. Make a new Cocoa Touch Class view controller named SearchViewController. Change the class code to this.
class SearchViewController: UIViewController { var count = 0 @IBOutlet weak var myLabel: UILabel! override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) myLabel.text = "Count \(count)" count += 1 } override func viewDidLoad() { super.viewDidLoad() count = 1 } }
Note how I used viewDidLoad
and viewWillAppear
here. In tab bar controllers, ViewDidLoad
only fires once, when we first load the view controller. Use it for first initializations only. The code above initializes the count to 1. The method viewWillAppear
fires every time the view appears, and so we use that to do any updating. This code assumes that this view controller will remain active even when it is not visible.
Go to the storyboard and select the Search view controller on your storyboard. In the identity inspector set the class to SearchViewController.
On the search view controller in the storyboard drag a label to the center of the view.
Set the label font size to 32 points. Click the auto layout align button at the bottom right of the storyboard. In the menu that appears, check Horizontally in Container and Vertically in Container with values of 0 points. Set Update Frame to Items of New Constraints.
Add the two constraints. Open up the assistant editor. Drag from the circle next to the outlet to the label to connect it.
Build and run. Select the search tab, then another tab a few times. You will see the count increase every time you return to the search tab.
You can also embed navigation controllers into tab controllers. Stop the simulator and go back to the storyboard. Close the Assistant editor if it is open. Select the Pizza View Controller’s icon on the storyboard. In the drop down menu, select Editor>Embed in>Navigation Controller
The view controller changes into a Navigation controller with the tab bar icon. Attached to the navigation controller is a view controller.
On the view controller, Double click the center of the navigation controller bar. Change the title to Pizza!!!. Drag a bar button item to the upper left of the controller on the storyboard. Title it More Pizza.
Add another view controller, next to the one we just configured. Control-Drag from the bar button item to the new view controller. Set up a show segue. In the new view controller, Drag a Navigation item to the navigation bar. Change the item’s title to More Pizza!!!
Build and run. Select the Pizza tab and we have our navigation controller. Tap the More Pizza Button. The More Pizza!!! View Appears. Now go to another tab and then back to the Pizza tab. We remain on the More Pizza!!! view.
You can use navigation controllers inside a tab bar controller to your heart’s content. However, tab bar controllers can only be used once in a project, as the top level controller. Embedding more tab bar controllers does not work.
This is the basics of tab bar controllers. For more information on sharing between the controllers and a more extensive coding example, see Passing Data in Tab Bar controllers.
Category: Auto Layout and Size Classes, ios8, Swift Programming, Swift Swift, TutorialTags: autolayout, iPhone Programming, more, swift programming, Tab bar, tab bar icon color, Tab Bar Icons, Tab bar items, Tab bar more, Xcode, xibs in swift
This site uses Akismet to reduce spam. Learn how your comment data is processed.
This site may include links that provide monetary compensation to the owners of this site.
Pingback: How to Make a Tab Bar Controller in Swift 3.0 Code | Making App Pie
Hey! Is there any way I can customize the table view controller that’s generated by the extra tabs? Great tutorial by the way, thank you so much!
Nope. No access by the developer to my knowledge.
Hey, thanks for the excelent post! Is there any way I can customize the generated table view? Thanks again!
Nope, that is only under user control to my knowledge.
Pingback: Walkthrough iOS development for coder (Swift) – Updating – Dungttm's Blog
Excellent walkthrough! Thank you so much :D
I go to the tab bar controller from my initial view controller, and it defaults to the farthest on the left. How can I set it so when there is a segue to the tab view controller it is a different view controller than the default.
Great step by step guide! thanks for taking the time!
you are welcome
Hey, The color of tabs are grey thats make my images look dull, How can U change that to its original color?
the tab bar color changes in the tabBar Property. You can set the back ground to an image with your preferred colors by setting
tabBarController.tabBar.backgroundImage
or a color withtabBarController.tabBar.barTintColor
in your view controller. See https://developer.apple.com/documentation/uikit/uitabbar for the documentation on both.