天天看点

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地址