Custom tabbar programmatically

Viewed 1703

I'm trying to create a UITabBarController with custom UITabBar programmatically.

I already found a way to implement this, but do not like the solution.

I know this is also possible by using Storyboards and .xibs, but wants to do it programmatically.

This code works:

class TabbarController: UITabBarController {
    init() {
        let vc1 = UIViewController()
        vc1.view.backgroundColor = .red

        let item1 = UITabBarItem()
        item1.title = "Tabbar item"
        item1.tag = 0

        vc1.tabBarItem = item1

        super.init(nibName: nil, bundle: nil)

        // Transparent native tabbar
        UITabBar.appearance().backgroundImage = UIImage()
        UITabBar.appearance().shadowImage = UIImage()
        UITabBar.appearance().clipsToBounds = false

        viewControllers = [
            vc1
        ]

        // inject custom tabbar
        object_setClass(self.tabBar, CustomTabbar.self)
        (self.tabBar as! CustomTabbar).setup()
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError()
    }
}

class CustomTabbar: UITabBar {
    func setup() {
        backgroundColor = .green
    }
}

enter image description here

I would like to do something cleaner by using override like:

class TabbarController: UITabBarController {
    private let customTabBar = CustomTabbar()

    override var tabBar: UITabBar {
        return self.customTabBar
    }

    init() {
        let vc1 = UIViewController()
        vc1.view.backgroundColor = .red

        let item1 = UITabBarItem()
        item1.title = "Tabbar item"
        item1.tag = 0

        vc1.tabBarItem = item1

        super.init(nibName: nil, bundle: nil)

        // Transparent native tabbar
        UITabBar.appearance().backgroundImage = UIImage()
        UITabBar.appearance().shadowImage = UIImage()
        UITabBar.appearance().clipsToBounds = false

        viewControllers = [
            vc1
        ]
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError()
    }
}

class CustomTabbar: UITabBar {
    init() {
        super.init(frame: .zero)

        backgroundColor = .green
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError()
    }
}

enter image description here

Can anyone tell me why this doesn't work?

I also tried to lazy init customTabBar property.

0 Answers
Related