天天看點

Swift設定tabbar

指定RootViewControll

window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
       let tabbar = CQ_TabbarViewController.CustomTabBar()
        window?.rootViewController = tabbar
        window?.makeKeyAndVisible();
           
lass CQ_TabbarViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()


    }

     class func CustomTabBar()->UITabBarController {
        let viewControllerArray = ["CQ_HomeViewController","CQ_CommunViewController","CQ_QuestionViewController","CQ_OwnViewController"]
        let tabBarVC = CQ_TabbarViewController()

        let tabbarArray = ["首頁","發現","問答","我的"]
        let titleArray = ["首頁","發現","問答","我的"] 
        var index:Int = 
        //循環像tabbarcontroller中添加對應的子控制器
        for str in viewControllerArray{

            let vc = NSClassFromString(str) as! UIViewController.Type
            //擷取到對應的控制器類
            let viewcontroller = vc.self.init()
            //建立導航控制器
            let nav : UINavigationController = CQ_NavViewController(rootViewController: viewcontroller)
            tabBarVC.addChildViewController(nav)
            //設定對應的tabbaritem
            let normalStr:String = tabbarArray[index]
            let title:String = titleArray[index]
            let selectStr:String = normalStr+"Sele"
            nav.tabBarItem = UITabBarItem(title: title, image: CQ_ImageSource.getImgView(normalStr as NSString), selectedImage: CQ_ImageSource.getImgView(selectStr as NSString))
            nav.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red], for: UIControlState.normal)
            nav.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.orange], for: UIControlState.selected)
            index += 
        }
        //設定tabbar的背景
        tabBarVC.tabBar.isTranslucent=false
        tabBarVC.tabBar.barStyle = .black
        tabBarVC.tabBar.barTintColor = UIColor(patternImage: UIImage(named: "Main_tabBar_background")!)
        tabBarVC.tabBar.backgroundImage = UIImage(named: "Main_tabBar_background")
        return tabBarVC   

    }

}
           

這裡簡單實作了設定tabbarController其中有一個重點就是let viewControllerArray = [“CQ_HomeViewController”,”CQ_CommunViewController”,”CQ_QuestionViewController”,”CQ_OwnViewController”]對應的控制器中一定要加上@objc(目前控制器的類名)

@objc()修飾的類可以被OC方法調用 我在上面調用了NSClassFromString這個OC的方法,是以調用Swift的類需要使用這個函數修飾

Demo github位址