ios - 点击单元格时在 UITableViewCell 上打勾

标签 ios objective-c uitableview

我想在点击单元格时在 UITableViewCell 上打复选标记。

但是当点击一个单元格并滚动 tableView 时,其他单元格也会被选中。

(我认为这是因为 UITableViewCell 被重用了。)

我有这个代码。

ViewController.m

@property (nonatomic, strong) NSMutableArray* selectedItems;

- (void)viewDidLoad
{
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    self.selectedItems = [NSMutableArray array];
    if ([ud objectForKey:@"SelectedItems"] != nil) {
        self.selectedItems = [ud objectForKey:@"SelectedItems"];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString* cellIdentifier = @"Cell";
    CustomCell* cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (cell.isChecked == YES) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else if (cell.isChecked == NO) {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }    
    return cell;
}

//when tapping the cell, put a check mark
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell* cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
    cell.isChecked = YES;
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [self.selectedItems addObject:cell.titleLabel.text];
    NSUserDefaults* ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:self.selectedItems forKey:@"SelectedItems"];
    [ud synchronize];
}

自定义单元格.h

@property BOOL isChecked;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier;


我只想在选定的单元格上打勾。
我该如何解决?

最佳答案

问题是您将已检查/未检查的信息存储在您的单元格中,该单元格是 View ,而不是您的数据源,因此违反了 MVC 的基本原则(模型- View - Controller )范例。

相反,在您的 cellForRowAtIndexPath 中,您必须检查存储在用户默认值中的数据,然后决定是否应检查该单元格。

此外,我们假设您的类中有一个实例变量,它在加载 View 时从用户默认值读取数据,而不是访问每个单元格的用户默认值。还假设您的数据源具有这种结构(字典数组):

@[@"text" : @"firstCellText",  @"checked" : @NO},
  @"text" : @"secondCellText", @"checked" : @YES}]

您当然可以通过多种不同的方式来执行此操作,因此以上内容仅用于说明。

// cellForRowAtIndexPath
cell.accessoryType = 
 [datasource[indexPath.row][@"checked"] boolValue] ?
 UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone;

关于ios - 点击单元格时在 UITableViewCell 上打勾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792311/

相关文章:

ios - 如何使搜索栏像 Iphone 设置

ios - UITableView - 删除 "inactive"行的分隔符

iphone - 我如何重新创建 TweetBot 样式 'drop-down' 单元格菜单?

ios - 使用弱变量而不是强变量的好处

iphone - IOS - cellForRowAtIndexPath 跳过行

ios - TableView 复制图像?

ios - iOS DateFormatter dateFormat fromTemplate 中允许使用哪些格式说明符?

iphone - 我需要解析推送通知中的有效负载,但是如果用户按游戏图标而不是按通知,如何获取数据?

ios - UIImage 大于自定义 UITableViewCell

ios - Swift:TableviewController 中的三个原型(prototype)单元格将无法查看