在Swift中并不提倡使用Runtime,而是像其他语言一样使用反射(Reflect)。当然,目前Swift中的反射还没有其他语言中的反射功能强大,不仅远不及OC的Runtime,离Java的反射也有一定的距离。
Swift的反射机制是基于一个叫 Mirror 的 struct 来实现的//反射事例
//反射机制,取出类的名字,转换成类,还要强转成类的类型 //1.从Bundle取出项目的名字(命名空间 = “项目的名字”+“.”+"类名") //2.修改命名空间,TARGETS -> Build Setting -> 输入product name ->修改即可 print("\(Bundle.main.infoDictionary)") let clsN = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? "" //3.let class NSClassFromString(className) as? class.Type //4. let cls = class?.init() let clsName = clsN + ".ViewController" let cls = NSClassFromString(clsName) as? ViewController.Type let vc = cls?.init() window?.rootViewController = vc// let vc = ViewController()// window?.rootViewController = vc window?.makeKeyAndVisible()//2.//MARK:添加子控制器 //反射机制,将控制器的属性添加到字典数组中,然后再创建一个存储有控制器的数组A,遍历存储有控制器所有属性的数组,并调用返回控制器的方法,添加到数组A中,并把数组赋值给viewControllers //----反射控制器的方法 //根据命名空间+"."+"类名"反射出类 //再设置类的title,image,文字大小 //再创建导航将根控制器添加上去,返回导航 func setupChildViewController (){ let array = [["clsName":"SinaHomeViewController","title":"首页","imageName":"tabbar_home"],["clsName":"SinaHomeViewController","title":"信息","imageName":"tabbar_message_center"], ["clsName":"","title":"","imageName":""], ["clsName":"SinaHomeViewController","title":"发现","imageName":"tabbar_discover"],["clsName":"SinaHomeViewController","title":"我","imageName":"tabbar_profile"]] var arrayVc = [UIViewController]() for dict in array{ arrayVc.append(addViewController(dict: dict)) } viewControllers = arrayVc } func addViewController(dict:[String:String])-> UIViewController{ //判断字典中是否有title,类名,imageName guard let clsName = dict["clsName"], let title = dict["title"], let imageName = dict["imageName"], let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type else{ return UIViewController() } let vc = cls.init() vc.title = title vc.tabBarItem.image = UIImage(named: imageName) vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(.alwaysOriginal) vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.black], for: .normal) let nav = SinaNavController(rootViewController: vc) return nav }