zoukankan      html  css  js  c++  java
  • Swift反射机制实现 AppDelegate 字符串获取类并成为根控制器

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
            
            window = UIWindow(frame: UIScreen.main.bounds)
            
            // 依据String名字拿到控制器(添加项目名称,命名空间,不能有数字和特殊符号)
            // 返回的是AnyClass? 需要as?强转
            // 控制器添加Type类型
            let rootControl = NSClassFromString("SwiftyDemo.ViewController") as? UIViewController.Type
            
            let vc = rootControl?.init()
            
            window?.rootViewController = vc
            
            window?.makeKeyAndVisible()
             
            return true
        }

       同时可以用info.plist获取命名空间

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
            window = UIWindow(frame: UIScreen.main.bounds)
            
            // 依据String名字拿到控制器(添加项目名称,命名空间,不能有数字和特殊符号)
            // 返回的是AnyClass? 需要as?强转
            // 控制器添加Type类型
    //        let rootControl = NSClassFromString("SwiftyDemo.ViewController") as? UIViewController.Type
            
            // 获取命名空间的值,可选
            let str = Bundle.main.infoDictionary?["CFBundleName"] as? String ?? ""
            
            let con = NSClassFromString(str + "." + "ViewController") as? UIViewController.Type
            
            let vc = con?.init()
            
            window?.rootViewController = vc
            
            window?.makeKeyAndVisible()
             
            return true
        }
  • 相关阅读:
    centos 7 开放端口
    删除mysql 表中重复的数据
    约瑟夫问题
    Technocup 2020 Elimination Round 3题解
    DISCO Presents Discovery Channel Code Contest 2020 Qual题解
    Comet OJ
    Berlekamp-Massey算法
    CH定理与线性递推
    2020集训队作业板刷记录(一)
    模拟费用流
  • 原文地址:https://www.cnblogs.com/sgxx/p/6096766.html
Copyright © 2011-2022 走看看