ios - 以编程方式自定义标签栏
问题描述
我正在尝试以编程方式使用自定义 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 属性。
解决方案
推荐阅读
- c# - 如何取消等待阻塞调用的任务
- kubernetes - 在 kubernetes 上构建 kafka 集群后如何公开 kafka 以供外部访问?
- scrapy - 按照链接结束 Scrapy 教程
- python - Python'未解决的导入键盘'。PyInstaller
- python - 如何使用日期时间变量名编写熊猫数据框
- go - 结构的方法签名之间的区别
- spring-boot - spring data elasticsearch可以加入父子关系吗?
- git - 将非新的本地分支推送到远程
- mysql - 在 MYSQL Workbench 中使用计数和平均值的项目列表产生的结果太少
- javascript - 输入后如何在按键上打印单词