4.4. Receiving and Handling Table View Events

Problem

You would like to respond to various events that a table view can generate.

Solution

Provide your table view with a delegate object.

Here is an excerpt of the .h file of a view controller with a table view:

#import <UIKit/UIKit.h>

@interface Receiving_and_Handling_Table_View_EventsViewController
           : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *myTableView;

@end

The .m file of the same view controller implements a method defined in the UITableViewDelegate protocol:

- (void)        tableView:(UITableView *)tableView
  didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

  if ([tableView isEqual:self.myTableView]){

    NSLog(@"%@",
    [NSString stringWithFormat:@"Cell %ld in Section %ld is selected",
     (long)indexPath.row, (long)indexPath.section]);
  }

}

- (void)viewDidLoad {
  [super viewDidLoad];

  self.myTableView = [[UITableView alloc]
                      initWithFrame:self.view.bounds
                      style:UITableViewStylePlain];

  self.myTableView.autoresizingMask =
    UIViewAutoresizingFlexibleHeight |
    UIViewAutoresizingFlexibleWidth;

  self.myTableView.dataSource = self;
  self.myTableView.delegate = self;

  [self.view addSubview:self.myTableView];

}

Discussion

While a data source is responsible for providing data to the table view, the table view consults the delegate whenever an event occurs, or if the table view needs further information before it can complete a task. For instance, the table view invokes a delegate’s method:

  • When and before a cell is selected or deselected

  • When the table view needs to find the height of each cell

  • When the table view needs to construct the header and footer of every section

As you can see in the example code in this recipe’s Solution, the current object is set as the delegate of a table view. The delegate implements the tableView:didSelectRowAtIndexPath: selector in order to get notified when the user selects a cell or a row on a table view. The documentation for the UITableViewDelegate protocol in the SDK shows you all the methods that the delegate can define and the view can invoke.

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.