iPhone问题:如何将一个按钮添加到tableview单元格?
问题描述:
小背景下,表视图由一个fetchedResultsController填充,它使用Strings填充表视图。现在我试图在每个tableview单元格中的每个字符串旁边添加一个按钮。到目前为止,我一直试图在configureCell:atIndexPath方法中创建一个按钮,然后将该按钮作为子视图添加到表格单元格的内容视图中,但出于某种原因,按钮不显示。以下是相关的代码。如果有人想要更多的代码发布,只需要问,我会提出任何你想要的。任何帮助是极大的赞赏。iPhone问题:如何将一个按钮添加到tableview单元格?
- (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;
}
答
三种意见:
- 您可能需要设置
UIButton
的框架。否则,它不知道它应该有多大以及它应该放在哪里。它可能带有一个默认框架,但我没有调查过。 - 你正在泄漏你的按钮。呼叫后您不需要
retain
[UIButton buttonWithType:...];
- 您可以将多个按钮添加到同一个单元格。如果您正在重复使用单元格,则应首先调用
removeFromSuperview
的每个子视图cell.contentView
。
感谢您的回复,我将[UIButton buttonWithType]更改为 CGRect buttonFrame = CGRectMake(0,0,40,40); UIButton * button = [[UIButton alloc] initWithFrame:buttonFrame]; 但没有任何显示。你认为它可能被某些东西遮挡了吗? 编辑:它被遮挡了,我可以在其他字符串文本下看到一些文本。现在我只需要移动它。非常感谢您的帮助。 – Jake 2010-05-14 17:41:43
'+ buttonWithType:'是'UIButtons'的正确初始值设定项。你只需要做一些事情:'[button setFrame:CGRectMake(0,0,40,40)];'afterwardswards – 2010-05-14 19:08:32