Jake
Jake

Reputation: 733

iPhone question: How can I add a button to a tableview cell?

Little background, the table view is filled by a fetchedResultsController which fills the table view with Strings. Now I'm trying to add a button next to each String in each tableview cell. So far, I've been trying to create a button in my configureCell:atIndexPath method and then add that button as a subview to the table cell's content view, but for some reason the buttons do not show up. Below is the relevant code. If anyone wants more code posted, just ask and I'll put up whatever you want. Any help is greatly appreciated.

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {

// get object that has the string that will be put in the table cell
 Task *task = [fetchedResultsController objectAtIndexPath:indexPath];

 //make button
 UIButton *button = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
 [button setTitle:@"Check" forState:UIControlStateNormal];
 [button setTitle:@"Checked" forState:UIControlStateHighlighted];

 //set the table cell text equal to the object's property
 cell.textLabel.text = [task taskName];

 //addbutton as a subview
 [cell.contentView addSubview:button];
 }

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

 static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }

 // Configure the cell.
 [self configureCell:cell atIndexPath:indexPath];
    return cell;
}

Upvotes: 2

Views: 3564

Answers (1)

Dave DeLong
Dave DeLong

Reputation: 243146

Three comments:

  1. You'll probably need to set the frame of your UIButton. Otherwise it doesn't know how big it's supposed to be and where it's supposed to be placed. It's possible that it comes with a default frame, but I haven't investigated that.
  2. You're leaking your buttons. You don't need to retain after calling [UIButton buttonWithType:...];
  3. You have the possibility of adding multiple buttons to the same cell. If you're reusing a cell, then you should first invoke removeFromSuperview each subview of cell.contentView .

Upvotes: 2

Related Questions