Displaying a Disclosure Button
The rows in a Table View can also optionally display additional buttons, such as the Detail Disclosure Button shown in Figure 15.
To display the disclosure button, you need to set the UITableView object's accessoryType property in the tableView:cellForRowAtIndexPath: method. Add the following code to the method:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
//...
UIImage *image = [[UIImage imageNamed:@"USA.jpeg"]
_imageScaledToSize:CGSizeMake(30.0f, 32.0f)
interpolationQuality:1];
cell.imageView.image = image;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
A detail disclosure button has two clickable regions: the row and the button itself. A user click on a row still fires the tableView:didSelectRowAtIndexPath: method (just like the previous examples). But a click on the detail disclosure button fires the tableView:accessoryButtonTappedForRowWithIndexPath: method instead. Therefore, you need to modify the tableView:didSelectRowAtIndexPath: method as follows:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:
(NSIndexPath *)indexPath {
NSString *stateSelected = [listOfStates objectAtIndex:
[indexPath row]];
NSString *msg = [[NSString alloc] initWithFormat:
@"You have selected %@", stateSelected];
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"State selected"
message:msg
delegate:self
cancelButtonTitle: @"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
[msg release];
}
You also need to implement the tableView:accessoryButtonTappedForRowWithIndexPath: method as follows:
- (void)tableView:(UITableView *)tableView
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
NSString *stateSelected = [listOfStates objectAtIndex:
[indexPath row]];
NSString *msg = [[NSString alloc] initWithFormat:
@"You have selected %@",
stateSelected];
//---Navigate to the details view---
if (self.detailsViewController == nil)
{
DetailsViewController *d = [[DetailsViewController alloc]
initWithNibName:@"DetailsViewController"
bundle:[NSBundle mainBundle]];
self.detailsViewController = d;
[d release];
}
//---set the state selected in the method of the
// DetailsViewController---//
[self.detailsViewController initWithTextSelected:msg];
[self.navigationController
pushViewController:self.detailsViewController
animated:YES];
[msg release];
}
Press Command-R to test the application. Now, clicking on a row in the Table View displays the alert view, while clicking on the detail disclosure button navigates to the other View window.
At this point, you've seen the basic operations involved in creating, populating, and handling events for the Table View in the iPhone SDK. Fully understanding how the Table View works is important, because is a very versatile view. The next article in this iPhone development series will reveal some more Table View tricks.