Can I use multiple segments with one UITableViewDelegate?

I have a UITableView listing several types of objects, and I would like to switch to a different view depending on what type of object the user selects.

Is it possible to do this using multiple segments, and if so, how?

+7
source share
2 answers

Of course! Define all your segues on the storyboard, ctrl-dragging from the ViewController table (and not the row, TableViewController itself) for the next view. Give them IDs so you know who to call. When all your segues are defined visually, go to the code. In your tableView delegate, in didSelectRowAtIndexPath , just call the segment you want by checking indexPath.row :

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { switch (indexPath.row) { case 0: [self performSegueWithIdentifier:@"Segue0" sender:self]; break; case 1: [self performSegueWithIdentifier:@"Segue1" sender:self]; break; [...] default: break; } } 

Thus, a segue with the identifier "Segue0" will be started when the user selects the first row, etc.

You can also add the line: [tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] animated:YES]; at the beginning didSelectRowAtIndexPath so that the row does not remain selected after the user touched it!

Edit: this works for both static and dynamic cells! Be careful to ctrl-drag your segue from tableViewController, not from a cell!

+17
source

Alternative implementation:

  • Create a specialized reusable prototypeCell in the table view for each type of object that you are going to store (either drag a new cell object from the object library or click on an existing standard and copy / paste), Remember to fill in a unique identifier for each reusable cell, you need will separate them later (maybe by calling

    [tableView dequeueReusableCellWithIdentifier: @ "CellIdentifier0"];

inside

 (UITableViewCell *)tableView(UITableView *)tableViewcellForRowAtIndexPath:(NSIndexPath *)indexPath; 
  • Ctrl-click on each prototype cell and drag to create a segue for each

  • Seger will be automatically launched, they just have to process them, because they quit

This works if you have one transition to a cell for reuse, which is likely to cover many cases.

0
source

All Articles