在使用swift中tabbarcontroller的时候,使用映射去添加。
Bundle扩展
import Foundation
extension Bundle {
// 计算型属性类似于函数,没有参数,有返回值
var namespace: String {
return infoDictionary?["CFBundleName"] as? String ?? ""
}
}
tabbarController
import UIKit
class TWTabBarController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
// 添加子控制器
setupChildControllers()
}
}
extension TWTabBarController {
private func setupChildControllers() {
// 使用映射处理
let array = [
["clsName":"HomeViewController", "title":"首页", "imgName":"home"],
["clsName":"TowViewController", "title":"消息", "imgName":"message_center"],
["clsName":"ThreeViewController", "title":"发现", "imgName":"discover"],
["clsName":"FourViewController", "title":"我", "imgName":"profile"],
]
var arrayM = [UIViewController]()
for dict in array{
arrayM.append(controller(dict: dict))
}
viewControllers = arrayM
}
private func controller(dict:[String: String])-> UIViewController {
guard let clsName = dict["clsName"], let title = dict["title"], let imgName = dict["imgName"], let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
return UIViewController()
}
// 2 创建视图控制器
// 1> 将clsName转换成cls
let vc = cls.init()
vc.title = title
// 3. 设置图像
vc.tabBarItem.image = UIImage(named: "tabbar_" + imgName)
vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imgName + "_selected")?.withRenderingMode(.alwaysOriginal)
// 设置 tabbar标题颜色
// 4. 设置 tabbar 的标题字体(大小)
vc.tabBarItem.setTitleTextAttributes(
[NSAttributedStringKey.foregroundColor: UIColor.orange],
for: .highlighted)
// 系统默认是 12 号字,修改字体大小,要设置 Normal 的字体大小
vc.tabBarItem.setTitleTextAttributes(
[NSAttributedStringKey.font: UIFont.systemFont(ofSize: 12)],
for: UIControlState(rawValue: 0))
// 5 实例化导航控制器的时候,会调用 push 方法将 rootVC 压栈
let nav = TWNavigationController(rootViewController: vc)
return nav
}
}