OC中可以使用NSClassFromString将字符串直接转换为类名,在Swift中利用NSClassFromString不出意外结果都为nil,因为Swift中根据字符串转换的方法需要加上YourAppName,格式为”YouAPPName.类名”
写了一个类目,具体代码如下:
import Foundation
import UIKit
extension NSObject {
func swiftClassFromString(className: String) -> UIViewController! {
// get the project name
if let appName: String = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as! String? {
//拼接控制器名
let classStringName = "\(appName).\(className)"
//将控制名转换为类
let classType = NSClassFromString(classStringName) as? UIViewController.Type
if let type = classType {
let newVC = type.init()
return newVC
}
}
return nil;
}
}
调用:
//将控制器名转换为类
let vc = self.swiftClassFromString(className)
self.navigationController!.pushViewController(vc,animated: true)