Can I use multiple segues with one UITableViewDelegate?

守給你的承諾、 提交于 2019-11-27 21:37:28
rdurand

Of course ! Define all your segues on your storyboard, by ctrl-dragging from the tableViewController (not a row, the tableViewController itself) to the next view. Give them IDs, so you know which one to call. When all your segues are defined visually, go to the code. In your tableView's delegate, in didSelectRowAtIndexPath, simply call the segue 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;
    }
}

That way, the segue with the ID "Segue0" will be fired when the user selects the first row, and so on.

You can also add the line : [tableView deselectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:1] animated:YES]; at the beginning of didSelectRowAtIndexPath so 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 the tableViewController, not a cell !

An alternative implementation would be to:

  • Create a specialized reusable prototypeCell in the table view for each type of object you're going to store (either drag a new cell object from your Object Library, or click on the existing default one and copy/paste). Remember to fill in a unique Identifier for each reusable cell, you'll need to be able to tell them apart later on (probably making a call to

    [tableView dequeueReusableCellWithIdentifier: @"CellIdentifier0"];

inside

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

  • The segues will get fired automatically, just have to handle them as they get fired

This works if you have a single transition per reusable cell, which is likely to cover many cases.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!