0

我正在尝试为表格视图中的每个单元格添加一个自定义单选按钮。当我第一次查看表格视图时,我看不到任何单选按钮。但是当我向下滚动时,我可以在第一次加载视图时看到的初始单元格下方的每个单元格上看到单选按钮。一旦一个没有单选按钮的单元格消失,我返回查看该单元格,单选按钮就会出现。

这是我的这种方法的代码:

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *ImageCellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ImageCellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ImageCellIdentifier];
    cell.accessoryType = UITableViewCellAccessoryNone;
}
_radioBtn.frame = CGRectMake(275, 3,36,36);
_radioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[_radioBtn setImage:[UIImage imageNamed:@"Radio-Btn.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:_radioBtn];

NSString *cellValue = [_arrayRelat objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
cell.textLabel.textColor = [UIColor colorWithRed:(88.0/255.0) green:(88.0/255.0) blue:(89.0/255.0) alpha:1];

return cell;
}

如果你不明白这个问题,请告诉我。

4

1 回答 1

1

您正在用每个新单元格覆盖 _radioBtn !您应该为每个单元格创建一个新的 UIButton 实例,例如:

UIButton *radioBtn = [UIButton buttonWithType:UIButtonTypeCustom];
radioBtn.frame = CGRectMake(275, 3,36,36);
[radioBtn setImage:[UIImage imageNamed:@"Radio-Btn.png"] forState:UIControlStateNormal];
[cell.contentView addSubview:radioBtn];

你应该把它放在你的if (cell == nil)块中,为每个单元格只创建一次。

于 2012-08-24T19:59:13.357 回答