滚动时重复的单元格。我该怎么做以防止它?

时间:2015-04-17 04:32:22

标签: ios uitableview

我是iOS编程语言的新手。我尝试在每行使用带按钮的表。

  1. 当我点击第一个单元格中的按钮时,效果非常好。
  2. 但是当我向下滚动时,我没有点击的单元格也会出现点击。
  3. 我想在我点击的单元格中显示点击的按钮? 代码:

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:    (NSIndexPath *)indexPath{
    ClassifyCustomCell * cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    
    if ([[[arrayResult objectAtIndex:indexPath.row] objectForKey:@"COLABO_FLD_SRNO"] isEqualToString:@"I"]) {
        cell.editButton.hidden = YES;
        cell.folder_name.text = [[arrayResult objectAtIndex:indexPath.row] objectForKey:@"COLABO_FLD_NM"];
    }else{
        cell.editButton.hidden = NO;
        cell.folder_name.text = [[arrayResult objectAtIndex:indexPath.row] objectForKey:@"COLABO_FLD_NM"];
        cell.editButton.tag = indexPath.row;
        [cell.editButton addTarget:self action:@selector(editButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        cell.checkButton.tag = indexPath.row;
        [cell.checkButton addTarget:self action:@selector(checkButtonActoin:) forControlEvents:UIControlEventTouchUpInside];
    }
    return cell;
    

    }

    -(void)checkButtonActoin:(UIButton *)sender{
    if (sender.selected == YES) {
        sender.selected = NO;
    }else if(sender.selected == NO){
        sender.selected = YES;
    }else {
        sender.selected = NO;
    }
    

    }

1 个答案:

答案 0 :(得分:0)

UITableView重用新单元格的单元格子视图的状态。为了防止重复使用,只需在tableView:cellForRowAtIndexPath:中明确配置您的子视图。在您的情况下,您需要将按钮的selected属性设置为YES(如果已选中),并设置为NO(如果未选中)。

将NSMutableArray属性添加到视图控制器:

@property (strong, nonatomic) NSMutableArray *arrayForSelectedIndexPaths;

更改您的点按方式:

-(void)checkButtonAction:(UIButton *)sender{
    UITableViewCell *cell = (UITableViewCell *) sender.superview.superview...; //find appropriate number of superviews to get your cell
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (sender.selected) {
        sender.selected = NO;
        [self.arrayForSelectedIndexPaths removeObject:indexPath];
    }else {
        sender.selected = YES;
        [self.arrayForSelectedIndexPaths addObject:indexPath];
    }
}

然后在tableView:cellForRowAtIndexPath:中添加以下行:

cell.checkButton.selected = [self.arrayForSelectedIndexPaths containsObject:indexPath];