O'Reilly logo

iOS 5 Programming Cookbook by Vandad Nahavandipoor

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

3.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];
  
}

- (void)viewDidUnload{
  [super viewDidUnload];
  self.myTableView = nil;
}

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required