1

I would like to call a method when a UITableViewCell is selected/tapped. I could do it easily with a static table view, but it requires a UITableViewController 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 methodOne when the first cell was tapped, call the methodTwo when the second cell was tapped and so on..

As a first step I set the numberOfRowsInSection 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.

rihekopo
  • 3,241
  • 4
  • 34
  • 63
  • 1
    You need to implement all of the normal table view data source and delegate methods whether you use a `UITableViewController` or add your own table view to a `UIViewController`. – rmaddy Aug 17 '14 at 18:30

2 Answers2

3

You can create an array of NSStrings with method names in the order they should be called from their corresponding UITableViewCells.

NSArray *selStringsArr = @[@"firstMethod", @"secondMethod", @"thirdMethod];

Then create a selector in tableView:didSelectRowAtIndexPath: from the strings array and call it using performSelector:.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *selString = selStringsArr[indexPath.row];
    SEL selector = NSSelectorFromString(selString);

    if ([self respondsToSelector:@selector(selector)]) {
        [self performSelector:@selector(selector)];
    }
}

Of course, there are some limitations to using performSelector: which you can read here.

enigma
  • 865
  • 9
  • 22
2

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];
             break;
        default:
             break;
    }
}

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.

Chris Loonam
  • 5,735
  • 6
  • 41
  • 63