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.

2

1 Answer 1

-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
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm not using storyboards, forgot to mention
Look can be work. I don't test, someone down vote but let a comment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.