表视图scrolling/dequeueReusableCell问题

jit*_*ith 2 objective-c uitableview ios

我有一个表格视图和一个自定义单元格.单元格包含3个按钮(复选框类型).在按钮上单击我需要更改的相应按钮文本(选中/取消选中).我实现了这一点,但是当我点击顶部单元格上的第一个按钮并向下滚动时,底部的新单元格也有这个复选标记,当我滚动回到顶部时,复选标记被移动到下一个单元格..如何解决这个问题? ?

码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *strCellIdentifier = @"RemoteCell";


    RemoteCustomCell *cell = (RemoteCustomCell*)[tableView ![dequeueReusableCell][2]WithIdentifier:strCellIdentifier];
    if (cell == nil) {
        cell = [[RemoteCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCellIdentifier];
    }
    else    {
        cell = [cell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCellIdentifier];
    }

  [cell.btnCheck1 addTarget:self action:@selector(CheckButton1_Click:) forControlEvents:UIControlEventTouchUpInside];            
    }
    return cell;

}


- (void)CheckButton1_Click:(UIButton*)sender
{
    RemoteControllCustomCell *clickedCell = (RemoteControllCustomCell *)[[sender superview] superview];

    if(clickedCell.btnCheck1.selected)
    {      
        [clickedCell.btnCheck1 setTitle:@"O" forState:UIControlStateNormal];        
        clickedCell.btnCheck1.selected = NO;
    }
    else
    {      
        [clickedCell.btnCheck1 setTitle:@"X" forState:UIControlStateSelected];
        clickedCell.btnCheck1.selected = YES;
    }
}
Run Code Online (Sandbox Code Playgroud)

截图:

在此输入图像描述

在此输入图像描述

Yok*_*oko 5

在您的RemoteCustomCell.m文件中,您应该实现

- (void)prepareForReuse
{
     [super prepareForReuse];
     cell.btnCheck1.selected = NO;
}
Run Code Online (Sandbox Code Playgroud)

这样,重复使用的每个单元格都将其btnCheck1.selected值设置为NO,当您加载单元格时cellForRowAtIndexPath,只有当单元格可见并将其设置为该单元格时,才会将其设置为YES.

但是将所有值存储在NSMutableArray中是关键.没有将值存储在单元格中的事情,它们会在无法预见的基础上重复使用.将值添加到数组并用于[myArray objectAtIndex:indexPath.row];在单元格中打开这些值.

一个例子:

在viewDidLoad中的某个地方

NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:@"1", @"0", @"1", @"1", nil];
Run Code Online (Sandbox Code Playgroud)

在你的 cellForRowAtIndexPath

BOOL yesOrNo = [[myArray objectAtIndex:indexPath.row] boolValue];
Run Code Online (Sandbox Code Playgroud)

然后将button.selected设置为布尔值.