通过字符串创建对象

通过重写UITabBarControlleraddChildViewController函数,实现利用String(类名)生成相应对象

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    private func addChildViewController(VCName : String, title : String, iconName : String) {
        
        //获取命名空间
        guard let nameSpace = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
            return
        }
        
        //根据字符串获取对应的Class
        guard let VCClass = NSClassFromString(nameSpace + "." + VCName) else {
            return
        }
        
        //将对应的AnyObject转成控制器的类型
        guard let VCType = VCClass as? ViewController.Type else {
            return
        }
        //创建对应的控制器对象
        let childVC = VCType.init()
        
        //设置控制器属性
        childVC.title = title
        childVC.tabBarItem.image = UIImage(named: iconName)
        childVC.tabBarItem.selectedImage = UIImage(named: iconName + "_highlighted")
        
        //生成导航栏控制器
        let childNav = UINavigationController(rootViewController: childVC)
        
        //添加控制器
        addChildViewController(childNav)
        
    }
}

你可能感兴趣的:(通过字符串创建对象)