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

标签 iphone uitableview subview

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

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

最佳答案

三条评论:

  1. 您可能需要设置 UIButton 的框架。否则它不知道它应该有多大以及应该放置在哪里。它可能带有默认框架,但我还没有调查过。
  2. 你的按钮泄露了。调用[UIButton buttonWithType:...];
  3. 后不需要retain
  4. 您可以向同一单元格添加多个按钮。如果您要重用单元格,则应首先调用 removeFromSuperview cell.contentView 的每个 subview 。

关于iPhone 问题 : How can I add a button to a tableview cell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2836170/

相关文章:

iphone - 在 iOS 5 上阻止 AirPlay 镜像

iphone - iPhone应用程序存储解决方案

iphone这种情况下如何释放内存

ios - 如何确定 dequeueReusableCellWithIdentifier 返回的单元格是否在 iOS 6 中被重用?

iphone - 将触摸事件传递给 View Controller 的所有 subview

ios - 按钮操作不适用于 subview

ios - Swift - 在 AppDelegate 中添加 subview

iphone - Xcode 4 部署目标

ios - 静态 UITableView 中的节标题大小不均匀

ios - 在 UITableViewController 之外使用 NSFetchedResultsController