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.6. Creating Custom Table View Cell Accessories

Problem

The accessories provided to you by the iOS SDK are not sufficient, and you would like to create your own accessories.

Solution

Assign an instance of the UIView class to the accessoryView property of any instance of the UITableViewCell class:

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  
  UITableViewCell* result = nil;
  
  static NSString *MyCellIdentifier = @"SimpleCell";
  
  /* We will try to retrieve an existing cell
   with the given identifier */
  result = [tableView dequeueReusableCellWithIdentifier:MyCellIdentifier];
  
  if (result == nil){
    result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:MyCellIdentifier];
  }
  
  result.textLabel.text = [NSString stringWithFormat:@"Section %ld, Cell %ld",
                           (long)indexPath.section,
                           (long)indexPath.row];
  
  UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  button.frame = CGRectMake(0.0f, 0.0f, 150.0f, 25.0f);
  
  [button setTitle:@"Expand"
          forState:UIControlStateNormal];
  
  [button addTarget:self
             action:@selector(performExpand:)
   forControlEvents:UIControlEventTouchUpInside];
  
  result.accessoryView = button;
  
  return result;
  
}

As you can see, this code uses the performExpand: method as the selector for each button. Here is the definition of this method:

- (void) performExpand:(id)paramSender{
  /* Take an action here */
}

This example code snippet assigns a custom button to the accessory view of every row in the ...

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