更改一个可重用单元格的UITableViewController会影响其他单元格

mic*_*den 4 uitableview didselectrowatindexpath reuseidentifier ios

我有一个非常简单的UITableViewController子类,旨在向用户显示单元格中字母表中的字符.当用户按下单元格时,将其附件类型设置为选中标记.

#import "MTGTableViewController.h"

@interface MTGTableViewController ()

@property (nonatomic, strong) NSArray *data;

@end

@implementation MTGTableViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    _data = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G", @"H", @"I", @"J", @"K", @"L", @"M", @"N", @"O", @"P", @"Q", @"R", @"S", @"T", @"U", @"V", @"W", @"X", @"Y", @"Z"];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _data.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = _data[indexPath.row];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

@end
Run Code Online (Sandbox Code Playgroud)

表视图工作正常.我在我的原型单元格的故事板中设置了reuseIdentifier属性,在开始选择单元格之前,它们看起来都很好.

问题:当我选择任何一个单元格时,比如"A"单元格,当我向下滚动它们时,其他尚未可见的单元格也会被赋予复选标记.更糟糕的是,当我向上和向下滚动时,有时会删除单元格"A"上的复选标记并将其赋予单元格"B".

Nic*_*art 6

这是因为表视图重用单元格的方式.调用dequeueReusableCellWithIdentifier后,您需要确保清除附件项.例如:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"reuseIdentifier" forIndexPath:indexPath];

    // Configure the cell...
    cell.textLabel.text = _data[indexPath.row];
    cell.accessoryType = UITableViewCellAccessoryNone;

    return cell;
}
Run Code Online (Sandbox Code Playgroud)

虽然 - 进行此更改后,您将遇到不同的问题.由于此代码,单元格将"忘记"它被选中.因此,您需要实际更改设置了accessoryType的行,以检查该单元格是否被选中.


Dav*_*Cao 3

不久前我也遇到了这个问题,您需要添加另一个数组来跟踪标记的单元格。只需创建一个标记为 NSIndexPath 的数组即可。有点像:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
     if ([arrayOfMarked containsObject:indexPath]) {
         cell.accessoryType = UITableViewCellAccessoryNone;
     } else {
         cell.accessoryType = UITableViewCellAccessoryCheckmark;
     }
}
Run Code Online (Sandbox Code Playgroud)