Reputation: 542
It works fine in OC:
NSString *controllerName = @"SecondViewController";
Class clazz = NSClassFromString(controllerName);
UIViewController *viewController = [[clazz alloc] init];
[self.navigationController pushViewController:viewController animated:YES];
When I use swift:
let controllerName = "SecondViewController"
let controller:AnyClass = NSClassFromString(controllerName)!
let viewController = (controller as! UIViewController.Type).init()
navigationController?.pushViewController(viewController, animated: true)
It crashed at let controller:AnyClass = NSClassFromString(controllerName)!
Any ideas?
Upvotes: 0
Views: 386
Reputation: 542
Swift classes are namespaced now so instead of "SecondViewController" it'd be "AppName.SecondViewController"
let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
let controllerName = "SecondViewController"
let controller:AnyClass = NSClassFromString(nameSpace + "." + controllerName)!
let viewController = (controller as! UIViewController.Type).init()
navigationController?.pushViewController(viewController, animated: true)
Upvotes: 1