0

在我的应用程序中,我加载了一个带有数组的 tableView,并为每一行添加了一个 UIButton 作为我需要的子视图。我知道重用的单元格将添加按钮所以记住这一点我已经实现了 -cellForRowAtIndexPath 方法,如下所示

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{   
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"];
        if (!cell) {
            cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"];
        }
        [[cell.contentView subviews] 
                  makeObjectsPerformSelector:@selector(removeFromSuperview)];
                             //before adding button to the contentView I've removed allSubViews
        UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
        [btn setFrame:CGRectMake(142, 4, 28, 28)];

        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected];
        [btn setSelected:YES];
        [btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTag:indexPath.row];

        if (indexPath.row==1) {
            NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews);
        }
        [cell.contentView addSubview:btn];
        return cell;
}

我的问题是 TableView 第一次加载得很好但是当我滚动 TableView 时,即使在添加按钮作为子视图之前删除了子视图,我添加的按钮也会被删除,这有助于我完成这项工作

4

1 回答 1

10

似乎删除单元格内容视图的所有子视图会导致单元格在您设置文本时重新创建其单元格内容。我设法重现了该问题,并改用此方法解决了该问题:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"surgeon"];
  if (!cell) {
    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"surgeon"];
  }
  for(UIView *subview in cell.contentView.subviews)
  {
    if([subview isKindOfClass: [UIButton class]])
    {
      [subview removeFromSuperview];
    }
  }

  //before adding button to the contentView I've removed allSubViews
  UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
  [btn setFrame:CGRectMake(142, 4, 28, 28)];

  [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"infoicon.png"]] forState:UIControlStateSelected];
  [btn setSelected:YES];
  [btn addTarget:self action:@selector(checkbtnClicked:) forControlEvents:UIControlEventTouchUpInside];
  [btn setTag:indexPath.row];

  if (indexPath.row==1) {
    NSLog(@"CELL %@ CONTNTVEW %@",cell.subviews,cell.contentView.subviews);
  }
  cell.textLabel.font=[UIFont systemFontOfSize:12];
  cell.textLabel.text=@"A surgeon.";
  [cell.contentView addSubview:btn];
  return cell;
}

重要提示:如果您计划进行任何进一步的单元格自定义,您还需要在循环中手动删除它们。

于 2013-04-26T14:44:32.817 回答