
TableView (Part 2)
In this tutorial you will learn how to capture the events on clicking the rows of the table. Table isn’t just used to preset the data but it is often needed to do some action against the selection of a cell.
Here is an overview of the part 1, how Table view is created.
1) Declare the UITableView variable and map it to the actual table in interface builder.
2) Implement UITableViewDelegate and UITableViewDataSource protocols.
3) Assign delegate and data source to UITableView object.
4) Implement numberOfRowsInSection and cellForRowAtIndexPath datasource methods as follows:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return4; }- (UITableViewCell *)tableView:(UITableView *)ttableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *MyIdentifier = @"MyIdentifier"; //If a cell with this identifier already created then it will be reused UITableViewCell *cell = [ttableView dequeueReusableCellWithIdentifier:MyIdentifier]; if (!cell) { //If a cell with this identifier doesn't already created then it will be created and assigned an identofier cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease]; } // Index of the cell to be processed int index = indexPath.row; // Text is going to be set of the cell cell.text = [NSStringstringWithFormat:@"%i", index]; // Cell is returned which will be shown on table return cell; }
Now you will learn about another method named didSelectRowAtIndexPath which is called everytime when user select a cell. You have to implement this method in the same controller class. Following is a basic implementation of this methos which will show an alert to the user saying “Row# n is selected”.
-(void)tableView: (UITableView*) ttableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //Message to show. indexPath.row is the row number selected NSString* msg = [NSStringstringWithFormat:@"Row# %i is selected", indexPath.row]; // Creating an alert view with the message above UIAlertView *alertmsg = [[UIAlertViewalloc] initWithTitle:@"title"message:msg delegate:selfcancelButtonTitle:@"OK"otherButtonTitles:nil]; // Show the alert [alertmsg show]; // Releae the alert alertmsg release]; }
Now when a user will select any row an alert message will be shown. You can do in this method what ever you want according to your need. Following out put will be shown on selection of 2nd row:
Hope this tutorial has helped you understanding UITableView selection event. In next Part I’ll explain the basics of creating custom cells.

Visit Jonathan Crowe's Website
Visit Jonathan Crowe on Twitter













Subscribe to Posts

Leave Your Response