Swift通过类名创建对象

前端之家收集整理的这篇文章主要介绍了Swift通过类名创建对象前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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)
原文链接:https://www.f2er.com/swift/323501.html

猜你在找的Swift相关文章