How do I create a UITabBarController with a custom UITabBar class without using IB?

后端 未结 3 735
花落未央
花落未央 2020-12-16 13:03

I can create a UINavigationController with custom bar classes by using initWithNavigationBarClass:toolbarClass:. There doesn\'t seem to be an equi

3条回答
  •  执笔经年
    2020-12-16 13:27

    This is surprisingly hard! The best I've come up with is subclassing UITabBarController and then doing this in the init:

    super.init(nibName: nil, bundle: nil)
    
    object_setClass(self.tabBar, CustomTabBar.self)
    (self.tabBar as? CustomTabBar)?.setup()
    

    Unfortunately you can't set the class before the call to super.init (not in Swift anyway), and so by the time you change the class the init method has already been run and so won't be called on your custom subclass. To get around this, I've just added a setup() method to do all my customisation in.

    Another option in Swift is to extend UITabBar and do something like this:

    extension UITabBar {
    
        open override func willMove(toSuperview newSuperview: UIView?) {
            super.willMove(toSuperview: newSuperview)
            /// Customise in here.
        }
    
        // Modify the height.
        open override func sizeThatFits(_ size: CGSize) -> CGSize {
            return CGSize(width: size.width, height: 64.0)
        }
    }
    

    However this will affect all instances of UITabBar, so I prefer the first option.

提交回复
热议问题