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

I can create a UINavigationController with custom bar classes using initWithNavigationBarClass:toolbarClass: There seems to be no equivalent for a UITabBarController , so how can I get it to use a custom UITabBar class?

Every solution that I have seen so far does not fit, because either

  • He uses IB
  • It adds a second tab bar to the UITabBarController instead of modifying the existing one, or
  • UITabBarController and makes a new controller class.

I want to create a real UITabBarController created in code using a special class for the tab bar. How to achieve this?

+7
ios uitabbarcontroller
source share
3 answers

This is surprisingly difficult! The best I came up with is a subclass of UITabBarController , and then do it in init :

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

Unfortunately, you cannot set the class before calling super.init (not in Swift anyway), and therefore, by the time the class is init , the init method is already running and therefore will not be called in your custom subclass. To get around this, I just added the setup() method to complete all my settings.

Another option in Swift is to extend the 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.

+5
source share

I do not think that's possible.

The following is Apple's documentation tabbar UITabBarController property of UITabBarController .

You should never try to manipulate the UITabBar object itself stored in this property. If you try to do this, the tab bar view throws an exception. To configure items for the tab bar of an interface, you must assign one or more custom controller views to the viewControllers property. The tab bar collects the necessary elements of the tab bar from the view managers you specify.

The tab bar view provided by this property is intended only for situations where you want to display an action sheet using the showFromTabBar: class method UIActionSheet.

+1
source share

As far as I know, you cannot do this. Your best way to do this without IB is to have your own UIViewController (not to subclass UITabBarController) and then add your own subclass of UITabBar to this controller.

You can also view the controller hierarchy if you decide to follow this approach.

0
source share

All Articles