通过NSClassFromString动态创建TabBar控制器的子控制器,主要注意点在获取其类名时还需要在之前加上工程名。
//控制器的名字
let ctrlNames = [
"MainPageViewController",
"NearShopViewController",
"ChooseViewController",
"MyViewController"]
//标题
let titles = ["首页","附近","精选","我的"]
//tabbar图片
let normalImageNames = [
"icon_tab_shouye_normal",
"icon_tab_fujin_normal",
"icon_tab_selection_normal",
"icon_tab_wode_normal"];
//选中的tabbar图片
let selectedImageNames = [
"icon_tab_shouye_highlight",
"icon_tab_fujin_highlight",
"icon_tab_selection_highlight",
"icon_tab_wode_highlight"];
//动态创建对象
let projectName = Bundle.main.infoDictionary?["CFBundleName"] as! String
for i in 0..<ctrlNames.count
{
//类 通过NSClassFromString方法创建类,类的字符串为:工程名 + “.” + 类名
let cls = NSClassFromString(projectName + "." + ctrlNames[i]) as! UIViewController.Type
//创建控制器对象
let viewController = cls.init()
//创建导航控制器
let nav = UINavigationController(rootViewController: viewController)
viewController.title = titles[i]
viewController.tabBarItem.image = UIImage(named: normalImageNames[i])
viewController.tabBarItem.selectedImage = UIImage(named: selectedImageNames[i])
//添加子控制器
addChildViewController(nav)
}
网友评论