Search code examples
iphoneiosuitableviewdidselectrowatindexpath

How to implement action in didSelectRowAtIndexPath of UITableview?


On my view, I used to have few buttons and each button had an action associated with it.

    UIButton *testButton = [[UIButton alloc] initWithFrame:CGRectMake(120,300,90,90)];
    [testButton setBackgroundImage:[UIImage imageNamed:@"test.jpg"] forState:UIControlStateNormal];
    [testButton addTarget:self.view action:@selector(gotoProd:) forControlEvents:UIControlEventTouchUpInside];
    [testButton addt
    [scrollView testButton];

But now I am trying to replace all those buttons with the tableview with rows. I was able to populate the rows and I know one needs to use didSelectRowAtIndexPath for handling on select event of the cell. But how can I implement action:@selector(gotoProd:) in tableviews ?? Any help will be greatly appreciated.


Solution

  • The most straight-forward way would look like this:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
          switch (indexPath.row) {
            case 0:
                [self doRow0Action];
                break;
            case 1:
                [self doRow1Action];
                break;
            // etc...
    
            default:
                break;
        }
    }
    

    If you wanted to instead, you could initialize an array with SEL types:

    [actionArray addObject:@selector(doRowNAction)];
    

    then access it like this:

    [self performSelector:[actionArray objectAtIndex:indexPath.row] withObject:nil];