rihe rihe - 3 months ago 21
iOS Question

Calling methods when UITableViewCell is pressed

I would like to call a method when a

is selected/tapped. I could do it easily with a static table view, but it requires a
which is not good for me in this case, therefore I'm using a normal vc.

I have 10 specified methods like this:

- (void) methodOne {
NSLog(@"Do something");
- (void) methodTwo {
NSLog(@"Do something");


And I would like to call the
when the first cell was tapped, call the
when the second cell was tapped and so on..

As a first step I set the
to return 10 cells, but have no idea how could I connect the selected cells with the methods. Is there any quick way to do it? It would be a dirty solution to create 10 custom cells and set the every method manually for the custom cells, and there is no free place for it.

Answer Source

You can use this method for whenever any cell is tapped on the table view

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    NSInteger selectedRow = indexPath.row; //this is the number row that was selected
    switch (selectedRow)
        case 0:
             [self methodOne];

Use selectedRow to identify which row number was selected. If the first row was selected, selectedRow will be 0.

Don't forget to set the table view's delegate to your view controller. The view controller also has to conform to the UITableViewDelegate protocol.

@interface YourViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

As long as the table view has a data source and a delegate, it doesn't matter what kind of view controller it is on. All a UITableViewController really is is a UIViewController that already has a table view on it and is that table view's delegate and data source.