0

I have a class 'MyViewController.swift' and a string "MyViewController". How can I create an instance of that viewController from the string and push it in the navigation controller?

I've checked this answer (How to create an object depending on a String in Swift?) but it doesn't seem to do the trick.

Community
  • 1
  • 1
Marcos Griselli
  • 1,306
  • 13
  • 22
  • May be this helps: http://www.spanware.com/blog/files/81bb0532b7f5c9ce9d015abc9b50c0e5-0.html – dasdom Jul 28 '15 at 14:41
  • possible duplicate of [Swift language NSClassFromString](http://stackoverflow.com/questions/24030814/swift-language-nsclassfromstring) – Wez Jul 28 '15 at 14:47

1 Answers1

-2

Assuming you are working with storyboard, you could extend UIStoryboard like:

class func mainStoryboard() -> UIStoryboard {
    return UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
}

class func myViewController(s: String) -> UIViewController? {
    return mainStoryboard().instantiateViewControllerWithIdentifier(s) as? UIViewController
}

and then you can use it like

myVC = UIStoryboard.myViewController("controller")
myVC.view.frame = view.frame

view.addSubview(myVC.view)
addChildViewController(myVC)
myVC.didMoveToParentViewController(self)

or

let vc = getVC("controller")
vc!.modalTransitionStyle = UIModalTransitionStyle.CrossDissolve
self.presentViewController(vc!, animated: true, completion: nil)

Update: If you are not using storyboards, you can add a something like this to your controller:

func getVC(s: String) -> UIViewController {
    switch s {
    case "myVc":
        return MyVC() as! UIViewController
    default:
        // handle default case
    }
}
matthias
  • 947
  • 1
  • 9
  • 27