8

I have a table view controller and tapping on a cell can trigger one of many different types of push segues based on the type of data in the cell. The identifier of the correct segue is determined in tableView:didSelectRowAtIndexPath: and then the segue is triggered with self.performSegueWithIdentifier:

For one of those segues, I'd like to push another instance of the same view controller on to the navigation stack. Is this possible without having to drag a new view controller object of the same type onto the storyboard? So far, I have only been able to wire up a segue to the same view controller if I Ctrl + Drag from the table cell to the view controller. This is not what I want.

Fergal Rooney
  • 1,330
  • 2
  • 18
  • 31
  • 1
    possible duplicate of [Storyboard Segue From View Controller to Itself](http://stackoverflow.com/questions/9226983/storyboard-segue-from-view-controller-to-itself) – Gustavo Barbosa Oct 23 '14 at 16:44
  • 2
    Don't use a segue. Instantiate a new instance and push or present it in code. I don't think there's any way to see the segue (a line going from the controller back to the same controller) anyway, so there's no real advantage in using a segue. – rdelmar Oct 23 '14 at 17:05
  • I accepted Tatonka's answer below as it is a valid solution to my problem. Thanks for the link to the other question. I saw some really interesting answers, particularly this one as it does answer exactly what I needed: http://stackoverflow.com/questions/9226983/storyboard-segue-from-view-controller-to-itself#answer-16247976 – Fergal Rooney Oct 24 '14 at 08:52

3 Answers3

10

As suggested, I don't think a segue will work. Instead you can push a new instance of the same view controller programmatically, which will have the same effect as performing the segue. The difference is that segue delegate methods like prepareForSegue won't be called.

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyViewController *vc = [[MyViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
} 
Kyle Parent
  • 460
  • 3
  • 13
  • 10
    That is `MyViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"moneyVC"];` then do `[self.navigationController pushViewController:vc animated:YES];` – Michael Lorenzo Jan 21 '15 at 22:29
1

Complemeting answer above you can do this in Swift 3 using:

 let vc = ViewController()          
 self.navigationController?.show(vc, sender: nil)

If you are using storyboard you can use this:

let vc = self.storyboard?.instantiateViewController(withIdentifier: "ViewControllerID") as! YourViewController
self.navigationController?.show(vc, sender: nil)
afrodev
  • 1,244
  • 11
  • 11
1
  1. Create a Storyboard Reference in IB.
  2. Refer it to the view controller.
  3. Then you can create a segue from the view controller to the reference, which refers to itself.
Ting Yi Shih
  • 792
  • 2
  • 9
  • 19