views:

336

answers:

1

Hi guys,

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;
}
A: 

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 .
Dave DeLong
Thanks for the response, I changed the [UIButton buttonWithType] to CGRect buttonFrame = CGRectMake(0, 0, 40, 40);UIButton *button = [[UIButton alloc]initWithFrame:buttonFrame];but nothing is showing up. Do you think it might be be being obscured by something?Edit: It's being obscured, I can see some text under the other String text. Now I just need to move it. Thanks a lot for you're help.
Jake
`+buttonWithType:` is the proper initializer for `UIButtons`. You just need to do something like: `[button setFrame:CGRectMake(0,0,40,40)];` afterwards
Dave DeLong