Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

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

I can create a UINavigationController with custom bar classes by using initWithNavigationBarClass:toolbarClass:. There doesn't seem to be an equivalent for UITabBarController, so how do I get it to use a custom UITabBar class?

Every solution I've seen so far is unsuitable because either

  1. It uses IB
  2. It adds a second tab bar to the UITabBarController instead of changing its existing one, or
  3. It throws UITabBarController away and makes a new controller class.

I want a real UITabBarController created in code using a custom class for its tab bar. How do I achieve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...