美文网首页
【Swift】通过控制器名称取对应的Class

【Swift】通过控制器名称取对应的Class

作者: Richard_Wei | 来源:发表于2018-08-28 11:28 被阅读0次
extension UIViewController {
    func swiftClassFromString(className: String) -> UIViewController! {
        // get the project name
        if  let appName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as! String? {
            // 过滤无效字符 空格不转换的话 得不到准确类名
            let formattedAppName = appName.replacingOccurrences(of: " ", with: "_")
            //拼接控制器名
            let classStringName = "\(formattedAppName).\(className)"
            //将控制名转换为类
            let classType = NSClassFromString(classStringName) as? UIViewController.Type
            if let type = classType {
                let newVC = type.init()
                return newVC
            }
        }
        return nil;
    }
}

相关文章

网友评论

      本文标题:【Swift】通过控制器名称取对应的Class

      本文链接:https://www.haomeiwen.com/subject/lvqtpxtx.html