在做项目的时候,很经常要一次性自定义好多控制器,假如是OC的项目,你不仅要导入很多头文件,还要写好多重复的代码,这个是很浪费时间的,所以,我在写这样的代码时,很常用的一个方法就是,把控制器的名字保存在一个数组中,在适当的地方把他们遍历出来创建控制器,这样可以省去导入头文件这一步骤,个人还是蛮喜欢这一写法的,下面是OC的代码
此方法是不用导入头文件的
NSArray*childVCName =@[
@"CHHomeViewController",
@"CHDiscoveryViewController",
@"CHMessageViewController",
@"CHSettingViewController"
];
for(NSIntegeri =0; i < childVCName.count; i ++) {
UIViewController*vc = [[NSClassFromString(childVCName[i]) alloc] init];
CHNavigationViewController*nav = [[CHNavigationViewController alloc] initWithRootViewController:vc];
[self addChildViewController:nav];
}
当我在做swift项目时,又遇到类似的情况,我当然第一时间会想到用上面那种方法添加控制器啦,可是,可是,我发现swift中这样添加控制器跟OC还是有辣么一点点区别的,经过我的一番研究,整理swift的代码如下:
fileprivate func addControllers(){
letcontrollers = ["CHAllActivitiesViewController",
"CHMoreViewController",
"CHTipMeViewController",
"CHPhotoViewController",
"CHFriendsViewController",
"CHElectriPhotoViewController",
"CHDetailViewController"]
for controller in controllers {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"]as!String
let vcClass = NSClassFromString(namespace+"."+controller)!as!UIViewController.Type
let navigationVC = UINavigationController(rootViewController: vcClass.init())
addChildViewController(navigationVC)
}
}
当你兴冲冲地写完上面一段代码的时候,肯定马上会跑起来的,但是,但是,你不要那么着急,你必须还要去info.plist中更改一下配置才行,
等你配置好如上的东西之后,你尽管放心地把你的代码跑起来吧,肯定perfect!!!!
如果你想按部就班地添加控制器,我也是可以提供一份小小心意的,代码如下:
fileprivate func addControllers(){
let vc1 = CHAllActivitiesViewController()
let navi1 = UINavigationController(rootViewController: vc1)
addChildViewController(navi1)
let vc2 = CHTipMeViewController()
let navi2 = UINavigationController(rootViewController: vc2)
addChildViewController(navi2)
let vc3 = CHPhotoViewController()
let navi3 = UINavigationController(rootViewController: vc3)
addChildViewController(navi3)
let vc4 = CHFriendsViewController()
let navi4 = UINavigationController(rootViewController: vc4)
addChildViewController(navi4)
let vc5 = CHElectriPhotoViewController()
let navi5 = UINavigationController(rootViewController: vc5)
addChildViewController(navi5)
let vc6 = CHMoreViewController()
let navi6 = UINavigationController(rootViewController: vc6)
addChildViewController(navi6)
let vc7 = CHDetailViewController()
let navi7 = UINavigationController(rootViewController: vc7)
addChildViewController(navi7)
}
看起来倒是整洁,可是,逼格就不够啦,你懂的!