swift-映射添加控制器

來源:互聯網
上載者:User

在使用swift中tabbarcontroller的時候,使用映射去添加。

Bundle擴充

import Foundationextension Bundle {    // 計算型屬性類似於函數,沒有參數,有傳回值    var namespace: String {        return infoDictionary?["CFBundleName"] as? String ?? ""    }}

tabbarController

import UIKitclass 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    }}
相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.