当我向上或向下滚动时,UITableViewCell的自定义图片会冻结

时间:2014-05-14 14:48:18

标签: objective-c uitableview

我在UITableViewCells上插入自定义UIButton,当我点击它时,UIButton的图片更改为复选标记,当我再次触摸它时,它转到未经检查的图片。当我滚动UITableView然后我不能让他们取消选中,根本无法改变图片。当我向上滚动时,它就像是图片变得冻结了。我的代码如下。

-(void)insertButtonOnCellTw:(UITableView *)tableView IndexPath:(NSIndexPath *)indexPath Cell:(UITableViewCell *)cell {



UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(actionButtonOnCellTw:)
 forControlEvents:UIControlEventTouchDown];
button.tag=indexPath.row;
[button setImage:[UIImage imageNamed:@"imgEmptyCheck.png"] forState:UIControlStateNormal];
button.frame = CGRectMake(285.0f, 20.0f, 35.0f, 35.0f);
[cell addSubview:button];

}

-(void)actionButtonOnCellTw :(id)sender
{
 UIButton *but=(UIButton*)sender;
 NSNumber *intIndexPathRow=[NSNumber numberWithInt:but.tag];
      if([masivCheckedTwCells containsObject:intIndexPathRow])
      {

        [but setImage:[UIImage imageNamed:@"imgEmptyCheck.png"] forState:UIControlStateNormal];
        [masivCheckedTwCells removeObject:intIndexPathRow];
    }
    else

    {
        [but setImage:[UIImage imageNamed:@"imgCheck.png"] forState:UIControlStateNormal];
        [masivCheckedTwCells addObject:intIndexPathRow];
    }


}

我可以像滚动清除所有带勾选标记的单元格并将它们再次置于“for”状态后解决它,但还有其他更明确的方法吗?

1 个答案:

答案 0 :(得分:0)

我解决了这个问题并希望分享,如果有人遇到同样的问题。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
当我向上滚动时,

方法会一遍又一遍地重复使用每个单元格,因此它不会创建新单元格而是重复使用它。 使用此代码,我可以在重复使用之前将其清理干净。

NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
for (UILabel *subview in subviews)
{
    [subview removeFromSuperview];
}
for (UIButton *subview in subviews) {
    [subview removeFromSuperview];
}
subviews = nil;

我的最后一个错误是我在这样的单元格上添加了按钮。[cell addSubview:button];但是最好将它添加到contentView,如[cell.contentView addSubview:button];