2

一点背景,表格视图由一个 fetchedResultsController 填充,它用字符串填充表格视图。现在我正在尝试在每个表格视图单元格中的每个字符串旁边添加一个按钮。到目前为止,我一直在尝试在 configureCell:atIndexPath 方法中创建一个按钮,然后将该按钮作为子视图添加到表格单元格的内容视图中,但由于某种原因,这些按钮没有显示出来。下面是相关代码。如果有人想要发布更多代码,请询问,我会提供您想要的任何内容。任何帮助是极大的赞赏。

- (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;
}
4

1 回答 1

2

三个评论:

  1. 您可能需要设置UIButton. 否则它不知道它应该有多大以及应该放置在哪里。它可能带有默认框架,但我没有对此进行调查。
  2. 你在泄露你的按钮。retain调用后不需要[UIButton buttonWithType:...];
  3. 您可以将多个按钮添加到同一个单元格。如果您正在重用一个单元格,那么您应该首先removeFromSuperview调用cell.contentView.
于 2010-05-14T17:28:45.570 回答