3. Patching the Screens in the Tab Bar
We have three screens. Now we want to patch these three screens in a Tab Bar Controller. Now it's time to use our main ViewController.swift file.
Let's look into the logical structure of a Tab Bar:

The Tab Bar is the UI component that displays the bottom tabs.
So it needs a controller to control the UI. In our case, we will use the main ViewController as the Tab Bar Controller.
The Tab Bar contains the bar items. In our case, we will use three bar items: red, green, and blue.
Each bar item represents a screen; for example, the red item represents the Red Screen.
Since each screen is independent of other tab bar screens, they should also have their own Navigation Controllers. (Do you remember that we have been embedding Navigation Controllers through the Storyboards? We can also do that by writing codes)
For each screen, we define its Navigation Controller, then embed it in the corresponding view controller.
We have already patched the screen views to their view controllers.
Setting up the Tab Bar: ViewController.swift
Let's open the ViewController.swift file and put the following code there:
In the above code:
We first need to adopt two protocols related to the Tab Bar Controller:
UITabBarController and UITabBarControllerDelegate(line 10).We should write the logic for setting up the tab bar controller just before the view appears. So we will write the code in
viewWillAppear()method.On lines 15 through 23, we set up the Tab Bar Button for the Red Screen.
On line 16, we define the Navigation Controller,
tabRedfor the Red Screen.Then we define the tab bar item.
We used two images from the SF Symbols app for two behaviors of the bar item: 'not selected' and 'selected'. It means when the user taps on an item, it should change its appearance with a different image. (Tab bar items are very similar to buttons).
On line 22, we set the tab bar item in the navigation controller,
tabRed.On line 23, we set the screen title for the red screen using the navigation controller.
We do the same steps for the other two screens from lines 25 through 43.
On line 46, we finally embed all three navigation controllers into this view controller.
If we run the app now, we will see:

Last updated
Was this helpful?