Carpetfizz
Carpetfizz

Reputation: 9149

Pass tableviewcell data with segue?

I have a popover segue that goes to a view controller. I want to set some properties in the view controller when a cell is clicked. I tried using -prepareForSegue:, but then I realized that it doesn't have the scope of the selected cell. I know that I have to use:

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath delegate method, but I'm not sure how that will affect the popover segue. Do I have to programatically create the popover, or is there another way?

Thanks much!

~Carpetfizz

Upvotes: 0

Views: 1971

Answers (3)

matteodv
matteodv

Reputation: 3982

The best approach is to use the indexPathForSelectedRow property.
For example you can write a code like this:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"YourSegueIdentifier"])
    {
        NSIndexPath *indexPath = [sender indexPathForSelectedRow];
        NextViewController *vc = (NextViewController *)segue.destinationViewController;
        vc.yourProperty = @"Some Value";
    }
}

Assuming NextViewController as your segue destination controller and yourProperty as the property you want to set during the segue, you can access and set information from your parent controller because indexPathForSelectedRow automatically knows which cell has been clicked.
More information can be found here.

Upvotes: 0

nekno
nekno

Reputation: 19267

Use self.tableView.indexPathForSelectedRow to get the data from your table's data source, e.g., the array backing the table data. If, for some reason, you don't want to get the data from your data source, then the sender is the UITableViewCell that was tapped to trigger the segue.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"YourSegueID"]) {
        YourDestinationViewControllerClass* destinationController = segue.destinationViewController;
        destinationController.somePublicProperty = self.yourTablesDataSourceArray[self.tableView.indexPathForSelectedRow.row];

        UITableViewCell *cell = (UITableViewCell *)sender;
        destinationController.someOtherPublicProperty = cell.textLabel.text;
    }
}

Upvotes: 3

Duncan C
Duncan C

Reputation: 131398

So add an NSIndexPath propriety to your VC. Let's call it selectedCell. In your tableView:didSelectRowAtIndexPath method, save the selected index path to the instance variable.

Then in your prepareForSegue method, use the instance variable.

Alternately, in your prepareForSegue method, you could ask the table view for the currently selected row using the table view's indexPathForSelectedRow method.

Upvotes: 1

Related Questions