views:

515

answers:

1

I am still in the process of getting myself acquainted with the iPhone SDK.

This is what I am trying to do :

I have a UIScrollView and each scroll view has an UITableView and I have implemented a custom UITableViewCell.

The desired functionality is initially there is no selection, then the user selects the row and scrolls and makes another selection in the next scroll view and continues. I want the selection to stay, so the user can change the selection at a later point.

However what is happening in my case is - the first and the second UITableViews are fine, the selected row stays selected, but in the third UITableView I see a row "already" selected which is same as the first UITableView. I do not want to see any selected.

I know I am doing something stupid but cannot figure out what. Any help would be really appreciated.

Thanks, Amy

Here are the relevant data source and delegate methods.



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
 NSLog(@"%s", __FUNCTION__);
 static NSString * ChoiceTableCellIdentifier = @"ChoiceTableCellIdentifier";
 choiceTableCell = (ChoiceTableCell *)[tableView dequeueReusableCellWithIdentifier:ChoiceTableCellIdentifier]; 
 if( choiceTableCell == nil )
 {
  choiceTableCell = [[[ChoiceTableCell alloc] 
       initWithFrame:CGRectZero
       reuseIdentifier:ChoiceTableCellIdentifier] autorelease];
 }
 return choiceTableCell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 NSLog(@"%s", __FUNCTION__);
 int newRow = [indexPath row];
 int oldRow = [lastIndexPath row];
 if ( (newRow != oldRow) || (newRow == 0) )
 {
        UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];
  UIImageView *indicatorN = (UIImageView *)[newCell.contentView viewWithTag:SELECTION_INDICATOR_TAG_1];
  indicatorN.image = [UIImage imageNamed:@"selected.png"];
  newCell.backgroundView.backgroundColor = [UIColor clearColor];

        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
  UIImageView *indicatorO = (UIImageView *)[oldCell.contentView viewWithTag:SELECTION_INDICATOR_TAG_1];
  indicatorO.image = [UIImage imageNamed:@"notSelected.png"];
  oldCell.backgroundView.backgroundColor = [UIColor clearColor];
        lastIndexPath = indexPath;
 }
}



+2  A: 

You are reusing a cell that has the image "selected.png". In the method cellForRowAtIndexPath you have to "select" or "deselect" your cell depending your last selection. That is: if indexPath is equals to lastIndexPath you have to put the background "selected.png", else "noSelected.png". When you reuse a cell, it keep its previous state, so you have to initialize it all.

Emanuel