Bienemann Bienemann - 1 year ago 67
iOS Question

iOS - Pushing to a View Controller that is not in the Storyboard

Ok, first let's name things:

I have a table view in my root view controller wich we'll call "HomeViewController". In that table view each cell tap will push a different view controller. This collection of view controllers we'll call "DetailViewControllers".

I am perfecly aware that I can make this work by simply loading and pushing each of the DetailViewControllers programmatically inside the didSelectRowAtIndexPath method. I want to do something different instead using storyboard and a prototype cell and I'm not succeeding, so I'm looking for some advice since I'm not too well versed in storyboards and segues.

The behavior I'm trying to achieve here is:
I'll have a segue from a prototype cell in the table view in my HomeViewController. That segue pushes a "base" view controller, from which every DetailViewController inherits. These view controllers don't have an assigned view controller in the storyboard either.

In the prepareForSegue method I want to cast the 'destinationViewController' to the 'right' class. The app crashes at that point saying it "Could not cast value of type 'BaseTestViewController' to 'TestViewController'.". Which is totally understandable.

So, my question is: is there a way to make a segue work like that?

Answer Source

You can't create segues programatically. Segues don't exist without a storyboard. You can just push to a view controller via loading a nib file.

Here's how you do it.

Let's say you have a nib file containing the layout of the view for the main view of your view controller. We'll name it "Test" for instance.

  1. Go to that nib file, click file's owner.enter image description here

  2. Change class to the name of your view controller. In my case, I named it ViewController.

enter image description here

  1. Right click on file's owner. Link the outlet of view of your view controller to the view in the nib file.

  2. Then in the view controller where you want to transition to that view controller, you do it like this:

    UIViewController *controller = [[UIViewController alloc] initWithNibName:@"Test" bundle:[NSBundle mainBundle]];

    [self presentViewController:controller animated:YES completion:nil];

It will present the view controller modally.

If you are embedding a navigation controller then you can do it like this:

[self.navigationController pushViewController:controller animated:YES];

Hope it helps.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download