Mehul Solanki
Mehul Solanki

Reputation: 463

Automatically select wrong cell in UITableView?

My Problem is, When I select a cell it automatically select other cell also. Also when I deselect that selected cell, automatically selected cell also be deselect. Any help is much appreciated. Thank you.

My Code is :

#pragma mark
#pragma mark UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
     return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [cellDataArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"customCellSearchBySpeciality";
    SpecialityCustomCell *cell = (SpecialityCustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SearchBySpecialityViewController" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    } 

    cell.cellData.text = [cellDataArray objectAtIndex:indexPath.row];
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    SpecialityCustomCell *selectedCell = (SpecialityCustomCell *)[tableView cellForRowAtIndexPath:indexPath];

    if (selectedCell.selectedCellImageView.image) {
        selectedCell.selectedCellImageView.image = nil;
    }
    else{
        [selectedCell.selectedCellImageView setImage:[UIImage imageNamed:@"image"]];
    } 
}

Upvotes: 0

Views: 930

Answers (1)

BhushanVU
BhushanVU

Reputation: 3455

I think you need to maintain instances of which cell you had aaded on each row then do selection and deselection on that particular object of cell's imageview like below,

 NSMutableArray *cellArray;

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifier = @"customCellSearchBySpeciality";
    SpecialityCustomCell *cell = (SpecialityCustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    [cellArray addObject:cell];

    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SearchBySpecialityViewController" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }

    cell.cellData.text = [cellDataArray objectAtIndex:indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    for(int cc=0;cc<[cellArray count];cc++){
    if(indexPath.row==cc){
    if ([cellArray objectAtIndex:cc].selectedCellImageView.image) {
        [cellArray objectAtIndex:cc].selectedCellImageView.image = nil;
    }
    else{
        [[cellArray objectAtIndex:cc].selectedCellImageView setImage:[UIImage  imageNamed:@"image"]];
    }
  }
}

Upvotes: 1

Related Questions