Search code examples
iosswiftuitabbaruitabbaritem

Create and Initialise Custom UITabBarItem Class


I am building an application with four UITabBarItems. They all should look the same. Instead of customising them in their respective UIViewController, I am trying to build a custom UITabBarItem class and have the UITabBarItems inherit from it.

So far, this is the work I have done:

class CustomTabBarItem: UITabBarItem {


    func customiseTabBarItems() {
        // Customises the item on the tab bar

        // For normal state
       setTitleTextAttributes([NSAttributedStringKey.font : Fonts.small!, NSAttributedStringKey.foregroundColor: Colours.grey], for: .normal)

        // When highlighted
       setTitleTextAttributes([NSAttributedStringKey.font : Fonts.small!, NSAttributedStringKey.foregroundColor: Colours.white], for: .highlighted)
    }


}

and I have set each UITabBarItem as a subclass of my 'CustomTabBarItem' in the storyboard.

The issue, however, is that the functionality is not showing up for my UITabBarItems.

Any advice?


Solution

  • I am building an application with four UITabBarItems. They all should look the same

    The way to make that happen is not to try some sort UITabBarItem subclass, but to use the appearance proxy for UITabBarItem. For example:

    UITabBarItem.appearance().setTitleTextAttributes( // ...
    

    Do that in your app delegate didFinishLaunching. All tab bar items will be customized in accordance with your commands to the appearance proxy.