My Swift 4 UITabBarController
usually has four UITabBarItem
items on it.
In certain circumstances it can have five instead of four, but I always want the far right button to be the same. That means I need to dynamically insert and/or remove the UITabBarItem
in the fourth "slot".
I'm able to handle adding and removing the UITabBarItem
in code with no problem, but I haven't been able to determine how to do it other than by using .append
, which only will add it to the fifth "slot".
Hours of poring over the Apple documentation and Stack Overflow have yielded no solution. How can I insert a UITabBarItem
at a specific index?
The UITabBarController
has a property called viewControllers
which is the array of viewControllers that it manages.
If you want to insert a new viewController (let's call it vc5
) at slot 4
, then you need to insert it into that array at index 3
since the counting starts at 0
:
myTBC.viewControllers?.insert(vc5, at: 3)
Likewise, to remove a viewController from the 4th slot:
myTBC.viewControllers?.remove(at: 3)
You can read more about working with UITabBarController
here. Also check out Array mutating functions insert(_:at:)
and remove(at:)
.