【Swift】通过控制器名称取对应的Class
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
网友评论