kusumoto_teruya
kusumoto_teruya

Reputation: 2475

UITableViewCell that I didn't edit (portion that is not visible) become also edited.

When I put a check mark on a UITableViewCell, the cell I didn't put checkmark (that is not visible) become also checked.
I think that when the tableview reuses cell, something is wrong.
How do I fix it?

- (void)viewDidLoad
{
    myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 100, 200, 300)];
    [myTableView registerClass:[AreaCellInShakeVC class] forCellReuseIdentifier:@"areaCell"];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    myTableView.allowsMultipleSelection = YES;
    [self.view addSubview:myTableView];

- (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];
    }
    return cell;
}

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

Upvotes: 0

Views: 42

Answers (2)

Gismay
Gismay

Reputation: 804

You need to have some logic in your cellForForIndexPath that sets the checkmark accordingly. This also means you need to store the status of the cell somewhere so you can check if it is ticked or not. So, set up an array, with an entry per row, then check that using your indexpath.row value to see if it should be checked or not. For example in cellForRowAtIndexPath have something like this

if ([[selectedRow objectAtIndex:indexPath.row] isEqualToString:@"Y"])
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark; 
}
else
{
    cell.accessoryType = UITableViewCellAccessoryNone;
}

In your didSelectRowAtIndexPath you can then set the check accordingly by

if ([[selectedRow objectAtIndex:indexPath.row] isEqualToString:@"Y"])
{
    [selectedRow replaceObjectAtIndex:indexPath.row withObject:@"N"];

}
else
{
    [selectedRow replaceObjectAtIndex:indexPath.row withObject:@"Y"];
}

Then do a reloadData on your tableView to update the checkMarks. Hope this helps.

Upvotes: 1

Viktor Kucera
Viktor Kucera

Reputation: 6335

Set up checkmark in cellForRowAtIndexPath like

cell.accessoryType = UITableViewCellAccessoryNone;

Upvotes: 0

Related Questions