在我的应用程序中,我加载了一个带有数组的tableView,并且我已经为每个行添加了一个UIButton作为我需要的subView。我知道重用的单元格会有添加的按钮所以记住这个事实我已经实现了-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时,我添加的Button已删除,即使在添加Button之前删除了subView,因为subView帮助我获得这项工作
答案 0 :(得分:9)
在设置文本时,删除单元格内容视图的所有子视图似乎会导致单元格重新创建其单元格内容。我已设法重现问题,并使用此方法修复它:
- (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;
}
重要提示:如果您计划进行任何进一步的单元格自定义,则还需要在循环中手动删除它们。