zoukankan      html  css  js  c++  java
  • Swift中字符串转化为Class的方法

    Swift中字符串转化为Class的方法

    在开发中有时候会根据字符串进行对应类的转化,这样我们就可以动态根据服务器返回的字段,动态的加载类,比如优酷,微博等APP会在节假日等动态的TabBar。这样可以把苹果审核的风险给排出。

    在OC中根据一段字符串转化为类,可以很方便的进行,只需要使用NSClassFromString 即可

    NSClassFromString(@"NewsViewController")
    

    但是在Swift中由于命名空间的存在导致这样的转化,会有一定的麻烦,我们可以用下面的方法进行转化。

    func getClass(stringName: String) -> Class {
    //根据字符串获取对应的class,在Swift中不能直接使用
    
    //Swift中命名空间的概念
    guard let nameSpage = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {
        print("没有命名空间")
        return
    }
    
    guard let childVcClass = NSClassFromString(nameSpage + "." + vcName) else {
        print("没有获取到对应的class")
        return
    }
    
    guard let childVcType = childVcClass as? UIViewController.Type else {
        print("没有得到的类型")
        return
    }
    
    //根据类型创建对应的对象
    let vc = childVcType.init()
    
    return vc
    

    }

  • 相关阅读:
    mySQL 重点
    JS代码预解析原理、函数相关、面向对象
    PHP中对数组进行操作的常用函数总结
    js函数和数组总结
    深入理解css网页布局细节
    AngularJS表单验证
    发送消息 缺少 更新的字段值
    springboot 下 logback + MDC的使用
    Mock的使用2
    StringUtils # split 的坑
  • 原文地址:https://www.cnblogs.com/fengtengfei/p/6104714.html
Copyright © 2011-2022 走看看