首页 > 解决方案 > 以编程方式自定义标签栏

问题描述

我正在尝试以编程方式使用自定义 UITabBar 创建一个 UITabBarController。

我已经找到了实现这一点的方法,但不喜欢该解决方案。

我知道这也可以通过使用 Storyboard 和 .xibs 来实现,但希望以编程方式进行。

此代码有效:

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
    }
}

在此处输入图像描述

我想通过使用覆盖来做一些更清洁的事情,例如:

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()
    }
}

在此处输入图像描述

谁能告诉我为什么这不起作用?

我也尝试懒惰地初始化 customTabBar 属性。

标签: iosswiftuikituitabbarcontrolleruitabbar

解决方案


推荐阅读