Swift通过类名创建对象
发布时间:2020-12-14 06:54:03 所属栏目:百科 来源:网络整理
导读:OC中可以使用NSClassFromString将字符串直接转换为类名,在Swift中利用NSClassFromString不出意外结果都为nil,因为Swift中根据字符串转换的方法需要加上YourAppName,格式为”YouAPPName.类名” 写了一个类目,具体代码如下: import Foundation import UIKit
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)
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |