← Back to Blog

Swift Navigation Basics: How to Setup a Tab Bar App

coding
mobile
tutorial

By Kevin Hou

7 minute read

The Basics

Setting up the Project

The “Main” Storyboard

Even if you decide to diffract your storyboards into multiple files, you must always have a storyboard named “main.storyboard.” Xcode automatically looks for this file when it loads so it is imperitive that it can find it, otherwise your app won't compile and/or could crash. Within that file you must have an initial view of some sort — this will be the first view that's loaded in your project.

Diffracting Into Multiple Storyboard Files

Connect the Tabs to the Storyboard

Connect the Storyboard Controller to the Swift View Controllers

Below are some additional customizations you can choose to add to your tab bar.

Setting a Custom Icon

Large Center Icon in Tab Bar

A lot of apps have a toolbar with a large center button that appears over the rest of the toolbar. It’s often a different shape and emphasizes the importance of that center tab. I recently figured out how to do this. Essentially you are creating a custom class for the tab bar and overlaying a button on top of the middle tab item. It creates a UIButton that blocks and replaces the functionality of the normal middle item.

swift navigation tab bar app

Here is the class:

1class CustomTabBarController: UITabBarController { 2 // Remember to the Tab Bar Controller custom class on your storyboard 3 override func viewDidLoad() { // Called when tab bar loads 4 super.viewDidLoad() 5 self.setupMiddleButton() // Sets up button 6 } 7 8 func setupMiddleButton() { 9 10 let menuButton = UIButton(frame: CGRect(x: 0, y: 0, width: 64, height: 64)) 11 12 var menuButtonFrame = menuButton.frame 13 menuButtonFrame.origin.y = self.view.bounds.height - menuButtonFrame.height 14 menuButtonFrame.origin.x = self.view.bounds.width/2 - menuButtonFrame.size.width/2 15 menuButton.frame = menuButtonFrame 16 17 menuButton.backgroundColor = UIColor.whiteColor() 18 menuButton.layer.cornerRadius = menuButtonFrame.height/2 19 20 menuButton.setImage(UIImage(named: "white-geo-flame"), forState: UIControlState.Normal) // 450 x 450px 21 menuButton.contentMode = .ScaleAspectFit 22 menuButton.addTarget(self, action: #selector(CustomTabController.menuButtonAction(_:)), forControlEvents: UIControlEvents.TouchUpInside) 23 24 self.view.addSubview(menuButton) 25 26 27 self.view.layoutIfNeeded() 28 } 29 30 func menuButtonAction(sender: UIButton) { 31 self.selectedIndex = 2 32 } 33} 34

Conclusion

A more decorated example of all of this can be found at: https://github.com/khou22/Swift-App-Templates/tree/master/SampleTabProject. A bare bones tab navigation app template can be found at https://github.com/khou22/Swift-App-Templates/tree/master/TabBarTemplate.