Find the answer below:
One of the typical usages of a UISegmentedControl is to use it like a tab view controller, where you want to switch between different view controllers. This post will demonstrate how to achieve this functionality in Swift through the UIViewController containment API, that allows embedding your UIViewController inside another. Also how to style your segmented control to look like a typical tab bar.While working on Zingoo, we had a requirement to switch between the photos and the info tabs through an Android-like tab bar. This was the target UI to achieve.
To achieve this, we had to have 3 different UIViewControllers, the parent (containing) view controller, and a view controller for each tab. We designed the 3 view controllers normally in the storyboard. The containing view controller will have a view that will contain the other view controllers views. We’ll call it “contentView”.
Let’s dive into code
We’ll need 2 IBOutlets, contentView and our segmented control.
Did you hear before about self.storyboard?
The first function we need, is a function that instantiates -or returns a cached instance- for the current selected tab index. We’ll make use of the self.storyboard to instantiate a view controller from our storyboard given the identifier.
From the documentation “A custom UIViewController subclass can also act as a container view controller. A container view controller manages the presentation of content of other view controllers it owns, also known as its child view controllers. A child’s view can be presented as-is or in conjunction with views owned by the container view controller.”
The second function, is the function responsible for establishing a parent-child relation between the containing view controller and the current child view controller to be displayed.
Note, your container view controller must associate a child view controller with itself before adding the child’s root view to the view hierarchy.
Now, we can start using this function in our viewDidLoad function to display the default tab.
Now, switching tabs is just a matter of removing the currentViewController and its view from the parent view controller, and then call our displayCurrentTab function.
TabBar Look and Feel
Now, it’s time for styling our UISegmetedControl to look like a tab bar.
Generally speaking, the appearance of the UISegmentedControl could be customized by using the following methods that set the background and divider images:
You’ll find more details on this topic on smnh.me, an excellent post really.
Final View Controller
Here’s how it looks on my demo app:
Here’s the final version of our container view controller.
Also, this is a ready demo app, check it: https://github.com/ahmed-abdurrahman/taby-segmented-control