6 tabs using UITabBarController

https://stackoverflow.com/questions/10313845/can-we-add-more-than-five-tab-bar-in-ios-sdk

final class TabBarController: UITabBarController, UITabBarControllerDelegate {

private var needsChangeTraitCollection: Bool {
         tabBarItems.count > 5
     }

...
override var traitCollection: UITraitCollection {
        if needsChangeTraitCollection > 5 {
            let traitCollection = super.traitCollection
            let regularTraitCollection = UITraitCollection(horizontalSizeClass: .regular)
            return UITraitCollection(traitsFrom: [traitCollection, regularTraitCollection])
        } else {
            return super.traitCollection
        }
    }
...
}

But there was a problem. When the other view controller is presented and the dark mode changes and the view controller is dismissed, the tab bar became to be only 5 tabs. But it was okay if tabBarController is the top view controller and the dark mode changes. So only when the traitCollection changes as the tabBarController is presenting other view controller the bug happened. So I forced to change trait collection when the tab bar controller’s viewWillAppear because it’s okay if the trait collection changes when the tab bar controller is on top.

final class TabBarController: UITabBarController, UITabBarControllerDelegate {
...
override func viewWillAppear(_ animated: Bool) {
         super.viewWillAppear(animated)

         if needsChangeTraitCollection {
             traitCollectionDidChange(traitCollection)
         }
     }
...
}

Calling traitCollectionDidChange when the real traitCollection is not changed does not trigger layoutSubviews.

And then another problem occurred. Even when the tabBar is shown and dark mode changes, the layout became strange…. It forces to change traitCollection from compact to regular before layout subviews.

override func viewWillLayoutSubviews() {
         if needsChangeTraitCollection {
             traitCollectionDidChange(traitCollection)
         }
         super.viewWillLayoutSubviews()
     }