如何在不使用IB的情况下使用自定义UITabBar类创建UITabBarController? [英] How do I create a UITabBarController with a custom UITabBar class without using IB?
问题描述
我可以使用initWithNavigationBarClass:toolbarClass:
创建具有自定义栏类的UINavigationController
.似乎没有等效的UITabBarController
,那么如何使用自定义的UITabBar
类呢?
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
- 它使用IB
- 它将第二个标签栏添加到
UITabBarController
而不是更改其现有的标签栏,或者 - 它会丢弃
UITabBarController
并创建一个新的控制器类.
- It uses IB
- It adds a second tab bar to the
UITabBarController
instead of changing its existing one, or - It throws
UITabBarController
away and makes a new controller class.
我希望使用自定义类的选项卡栏在代码中创建真实的UITabBarController
.我该如何实现?
I want a real UITabBarController
created in code using a custom class for its tab bar. How do I achieve this?
推荐答案
这很难做到!我想出的最好的方法是将UITabBarController
子类化,然后在init
中进行此操作:
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()
不幸的是,您无法在调用super.init
之前设置类(无论如何在Swift中都不会),因此,当您更改类时,init
方法已经运行,因此不会被调用在您的自定义子类上.为了解决这个问题,我刚刚添加了一个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.
Swift中的另一个选择是扩展UITabBar
并执行以下操作:
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)
}
}
但是这会影响UITabBar
的所有实例,所以我更喜欢第一种选择.
However this will affect all instances of UITabBar
, so I prefer the first option.
这篇关于如何在不使用IB的情况下使用自定义UITabBar类创建UITabBarController?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!