IPhone question: how to add a button to a tableview cell?
Little background, the table view is populated with a fetchedResultsController element that populates the table view with rows. Now I am trying to add a button next to every row in every cell of the tableview. So far I have tried to create a button in my configureCell: atIndexPath method and then add that button as a subview to the table cell content view, but for some reason the buttons are not showing. Below is the relevant code. If anyone wants to add more code, just ask and I'll put in whatever I want. Any help is 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 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;
}
+2
a source to share
1 answer
Three comments:
- You will probably need to frame your
UIButton
. Otherwise, he doesn't know how big it should be and where it should be placed. It may come with a default frame, but I haven't researched that. - You are missing your buttons. You don't need
retain
after calling[UIButton buttonWithType:...];
- You have the option to add multiple buttons to the same cell. If you are reusing a cell, you must call
removeFromSuperview
each subhead firstcell.contentView
.
+2
a source to share