添加到UITableViewCell的UIButton将无法显示

时间:2011-02-23 00:44:52

标签: iphone uitableview uibutton

在阅读了这里和其他地方的所有示例后,我编写了以下代码来向UITableViewCell添加一个按钮,但是我无法在单元格中显示它。我做错了什么?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   static NSString *CellIdentifier = @"Cell";

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
   }

UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)];
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal];
[cell.contentView addSubview:cellButton];
[cellButton release];
return cell;
}   

谢谢,约翰

2 个答案:

答案 0 :(得分:6)

无需在您通过release创建的按钮上拨打buttonWithType;通过调用release,你导致保留计数下降,并且在某些时候按钮将被破坏,然后你想要它。

答案 1 :(得分:2)

你做错了两件事。首先,正如上面的海报所说,你正在过度释放按钮,程序可能在将来崩溃。通常,静态方法将返回自动释放的对象,因此您不需要自己释放它(除非您事先保留它)。

此外,由于您正在重复使用tablecell,上面的代码会多次向单元格添加UIButton,这可能不是您想要的行为。初始化表格单元格时添加UIButton。此外,您可能需要确保按钮rect位于表格单元格内作为完整性检查。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

   static NSString *CellIdentifier = @"Cell";

   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
   if (cell == nil) {
       cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];

UIButton *cellButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[cellButton setFrame:CGRectMake(0.0f, 5.0f, tableView.frame.size.width-2, 44.0f)];
[cellButton setTitle:[aList objectAtIndex:indexPath.row] forState:UIControlStateNormal];      
[cell addSubview:cellButton];
   }

return cell;
}   
相关问题