根据字符串生成类---类的类型.self---根据字符串创建控制器对象

swift和OC一样,都是通过NSClassFromString,根据一个字符串,生成相应的类。

1 // UITabBarButton是系统的私有类,不能直接使用
2 // if btn.isKind(of: UITabBarButton.self){
3 if btn.isKind(of: NSClassFromString("UITabBarButton")!){
4      //   NSClassFromString:根据字符串取相应的类
5 }

取一个类的类型,oc中是[类 class],swift中[类.self]:

OC示例代码:

1 // oc中使用[类 class]取类的类型
2 [self.tableView registerClass:[ZFBFriendSHQCell class] forCellReuseIdentifier:cellID];

swift示例代码:

1 // swift中通过[类.self]取类的类型
2 tableView.register(WBHomeTableViewCell.self, forCellReuseIdentifier: WBHomeTableViewCellIdentifier)

根据字符串创建控制器对象:

swift中存在命名空间的概念,我们提供的控制器名必须要包含命名空间(项目名.控制器名),如:YS.YSCustomViewController

1         // 获取对应的class类型,注意,一定要加type
2         let classType = NSClassFromString("YS.YSCustomViewController")! as! UIViewController.Type
3         
4         // 根据class类型创建控制器对象
5         let viewController = classType.init()

 

原文地址:https://www.cnblogs.com/panda1024/p/6217005.html