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

2018-08-28  本文已影响0人  Richard_Wei
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;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读