Reputation: 583
So I am using some Storyboard References to bring in some structure. Now I am trying to change the ViewController from code, but I am not able to use a ViewController from a different Storyboard. My Code is currently looking like that:
func showCommunityDetail(){
let storyBoard : UIStoryboard = UIStoryboard(name: "community", bundle:nil)
let nextViewController = storyBoard.instantiateViewController(withIdentifier: "communityDetail") as! CommunityViewController
self.present(nextViewController, animated:true, completion:nil)
}
The community Storyboard contains the communityDetail controller, but the view which is shown at the moment this code is executed, is in a different storyboard.
How can I present between different Storyboards?
Update
I updated my code to the following line:
let detailViewController = UIStoryboard(name: "community", bundle: nil).instantiateViewController(withIdentifier: "communityDetail");
However, now i get a new error: whose view is not in the window hierarchy!
Upvotes: 0
Views: 115
Reputation: 296
Just worked on the requirement you asked for and it is in swift 2.2. Try it out it works this way.
var nextViewController : CommunityViewController!
func showCommunityDetail() {
let mainStoryboard = UIStoryboard(name: "community", bundle: nil)
nextViewController = mainStoryboard.instantiateViewControllerWithIdentifier("communityDetail") as! CommunityViewController
addChildViewController(nextViewController)
// Optionally you can change the frame of the view controller to be added
nextViewController.view.frame = CGRect(x: 0, y: 0 , width: view.frame.width, height: view.frame.height)
view.addSubview(nextViewController.view)
nextViewController.didMoveToParentViewController(self)
}
Upvotes: 0
Reputation: 13459
To present a view controller in a different storyboard.
1) Make sure the "Initial View Controller" property is set for the entry ViewController in each of the storyboards.
Present it:
let vcToPresent = UIStoryboard(name: "StoryboardName", bundle: nil).instantiateInitialViewController();
// Ensure its of the type that you want, so that you can pass info to it
guard let specialVC = vcToPresent as? SpecialViewController else {
return
}
specialVC.someProperty = somePropertyToPass
self.present(specialVC, animated: true, completion: nil)
Edit:
To instantiate a different viewcontroller (other than the one who is marked as initial) the following method can be used:
func instantiateViewController(withIdentifier identifier: String) -> UIViewController
Link to the documentation: https://developer.apple.com/reference/uikit/uistoryboard/1616214-instantiateviewcontroller
Note that you MUST set an identifier on the interface builder for the viewcontroller you want to use this method with.
Upvotes: 1