DonnellyOverflow
DonnellyOverflow

Reputation: 4195

Perform a segue from a UITableView to a new view controller Xamarin

I have a Xamarin.iOS application which includes a Navigation Controller where the root in a View Controller ViewController.cs, inside the UIViewController (the default one created in a single view application) is a Table View which has a segue to a new View Controller.

Depicted in Storyboard below.

ViewControllers

The Table view is controlled by the StationsTableViewSource.cs code which inherits from UITableViewSource. The source for the Table View is set inside the ViewController.cs.

StationsTable.Source = new StationsTableViewSource(StationPlayer.StationsTitleList)

When I press a cell in the table view I want to segue to the new view controller but as I see it:

  1. I have no access to the Parent/Root/Containing View Controller from the Table View
  2. I have no access to the New View Controller from the Table View.

My question is this, with a set up as above, how can I perform a segue from a cell inside a tableview nested in a View Controller to another View Controller?

Please correct the terminology - not too hot on Xamarin/iOS lingo.

Thanks all.

Upvotes: 1

Views: 1173

Answers (1)

Ax1le
Ax1le

Reputation: 6643

First of all, we need to figure out which segue have you created?

1.From your tableViewCell to a new ViewController.

This means: tap down on the Cell + ctrl and drag to a new ViewContoller. In this way, there's no need to execute PerformSegue() manually. When you click the Cell, it will push to a new Controller.

2.From your ViewContoller to a new ViewController

This means: tap down on the bottom bar of the ViewContoller + ctrl and drag to a new ViewController. In this way, we need to click the segue we created above then set the Identifier. When we click the Cell, the event below will be triggered:

public override void RowSelected(UITableView tableView, NSIndexPath indexPath)
{
    //use this method we can push to a new viewController
    //the first parameter is the identifier we set above
    parentVC.PerformSegue("NewPush", indexPath);
}

I have no access to the Parent/Root/Containing View Controller from the Table View

When you construct this Source you can pass your "Parent" ViewController like:

ViewController parentVC;
//You can add other parameters you want in this initial method
public MyTableViewCellSource(ViewController viewController, ...)
{
    parentVC = viewController;
}

Moreover both segues will fire PrepareForSegue() in the parent ViewController. In this method you can pass parameters to the new ViewController:

public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
{
    if (segue.Identifier == "NewPush")
    {
        SecondVC secondVC = segue.DestinationViewController as SecondVC;
        ...//do some configuration
    }
}

About how to use segue, you can read this official documentation for more details.

Upvotes: 3

Related Questions