在我的应用程序中,我加载了一个带有数组的 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 时,即使在添加按钮作为子视图之前删除了子视图,我添加的按钮也会被删除,这有助于我完成这项工作