In this Swift code example, you will learn how to create UITabBarController programmatically.
- We will first create two View Controllers which will be Tab 1 and Tab 2,
- and then we will create one more View Controller which will serve as UITabBarController and will hold the two tabs. When a user taps on tab 1, TabOneViewController will be loaded. When a user taps on tab 2, TabTwoViewController will be loaded.
Create ViewController For Tab 1
Below is a little code example in Swift that creates a new UIViewController that will be loaded when the user taps on a Tab 1.
import UIKit class TabOneViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.blue self.title = "Tab 1" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Create ViewController for Tab 2
When the user taps on Tab 2, the TabTwoViewController will be loaded. Below is a code example that creates a new UIViewController that will be loaded when the user taps on Tab 1.
import UIKit class TabTwoViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. self.view.backgroundColor = UIColor.red self.title = "Tab 2" } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Create UITabBarController
The following UIViewController will hold Tab 1 and Tab 2 and will implement the method didSelectViewController to handle an event when one of the tabs is selected.
import UIKit class ViewController: UITabBarController, UITabBarControllerDelegate { override func viewDidLoad() { super.viewDidLoad() //Assign self for delegate for that ViewController can respond to UITabBarControllerDelegate methods self.delegate = self } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Create Tab one let tabOne = TabOneViewController() let tabOneBarItem = UITabBarItem(title: "Tab 1", image: UIImage(named: "defaultImage.png"), selectedImage: UIImage(named: "selectedImage.png")) tabOne.tabBarItem = tabOneBarItem // Create Tab two let tabTwo = TabTwoViewController() let tabTwoBarItem2 = UITabBarItem(title: "Tab 2", image: UIImage(named: "defaultImage2.png"), selectedImage: UIImage(named: "selectedImage2.png")) tabTwo.tabBarItem = tabTwoBarItem2 self.viewControllers = [tabOne, tabTwo] } // UITabBarControllerDelegate method func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) { print("Selected \(viewController.title!)") } }
For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.