Search code examples
iosobjective-cuitableviewdidselectrowatindexpath

How to Change selected Cell data permanently?


I want to change the selected cell data permanently as i have done in my didSelectRowAtIndexPath method but the problem is that when I select a row the cell data is change but when i select any other row the previous become as it was, and I also want to save rows in an array, those been selected in an array. here is my code right now.

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
@try {
    static NSString *cellidentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellidentifier];
    if(cell == nil)
    {
        NSArray *cellObjects = [[NSBundle mainBundle] loadNibNamed:@"Cell" owner:self options:nil];
        cell = (UITableViewCell*) [cellObjects objectAtIndex:0];
    }

    UILabel *label;
    long row = [indexPath row];

    label = (UILabel *)[cell viewWithTag:10];

    label.text =time[row];
    label.textColor = [UIColor blackColor];
    cell.imageView.image = [img_clock_blue objectAtIndex:indexPath.row];
    cell.backgroundColor = [UIColor yellowColor];

    [tableView setSeparatorInset:UIEdgeInsetsZero];

    //int hecValue;
    return cell;
}
@catch (NSException *exception)
{
    NSLog(@"%@",exception);
}
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView reloadData];
UITableViewCell *cell1 = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
cell1.imageView.image = [UIImage imageNamed:@"1_red.png"];
cell1.backgroundColor = [UIColor clearColor];
}

Solution

  • Try this,

    1. create a NSMutableArray @property in view controller. lets say selectedIndexArray
    2. initialize the array in viewDidLoad by self.selectedIndexArray = [[NSMutableArray alloc] init];

    in cellForRowAtIndexPath method

    -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        //other codes
        if ([self.selectedIndexArray containsObject:indexPath]) {
             cell.imageView.image = [UIImage imageNamed:@"1_red.png"]; //assumes all selected cells have same image
        } else {
    
             cell.imageView.image = [img_clock_blue objectAtIndex:indexPath.row];
        }
    
        .....//other code
    }
    

    in didSelectRowAtIndexPath:

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        [self.selectedIndexArray addObject:indexPath];
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }