1 /// 類文件字符串轉換為ViewController 2 /// 3 /// - Parameter childControllerName: VC的字符串 4 /// - Returns: ViewController 5 func VCSTRING_TO_VIEWCONTROLLER(_ childControllerName: String) -> UIViewController?{ 6 7 // 1.獲取命名空間 8 // 通過字典的鍵來取值,如果鍵名不存在,那么取出來的值有可能就為沒值.所以通過字典取出的值的類型為AnyObject? 9 guard let clsName = Bundle.main.infoDictionary!["CFBundleExecutable"] else { 10 print("命名空間不存在") 11 return nil 12 } 13 // 2.通過命名空間和類名轉換成類 14 let cls : AnyClass? = NSClassFromString((clsName as! String) + "." + childControllerName) 15 16 // swift 中通過Class創建一個對象,必須告訴系統Class的類型 17 guard let clsType = cls as? UIViewController.Type else { 18 print("無法轉換成UIViewController") 19 return nil 20 } 21 // 3.通過Class創建對象 22 let childController = clsType.init() 23 24 return childController 25 }
以上代碼示例:
使用類的字符串轉為ViewController,以實際應用過!
