Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView selected cell doesn't stay selected when scrolled

Tags:

I'm having problems with table view cells not keeping their "selected" state when scrolling the table. Here is the relevant code:

@property (nonatomic, strong) NSIndexPath *selectedIndexPath;  -(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {     self.selectedIndexPath = indexPath;     //do other stuff }  -(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {      MyCustomCell_iPhone* cell = [tableView dequeueReusableCellWithIdentifier:@"MyCustomCell_iPhone"];      if (cell == nil)         cell = [[[NSBundle mainBundle] loadNibNamed:@"MyCustomCell_iPhone" owner:self options:nil] objectAtIndex:0];      if ([indexPath compare: self.selectedIndexPath] == NSOrderedSame) {         [cell setSelected:YES animated:NO];     }      return cell; } 

And for the cell:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {     [super setSelected:selected animated:animated];      if (selected) {         self.selectedBg.hidden = NO;     }else{         self.selectedBg.hidden = YES;     } }  - (void)setHighlighted:(BOOL)highlighted animated:(BOOL)animated {     [super setHighlighted:highlighted animated:animated];      if (highlighted) {         self.selectedBg.hidden = NO;     }else{         self.selectedBg.hidden = YES;     } } 

How can I get the selected cell to stay highlighted? If I scroll it off the screen, when it scrolls back on the screen it appears in its unselected state (with its selectedBg hidden).

EDIT: Removing the setHighlighted method from the cell fixes the issue. However that means that I get no highlighted state when pressing the table cell. I'd like to know the solution to this.

like image 480
soleil Avatar asked Nov 07 '12 17:11

soleil


1 Answers

Had the same problem, selected cell's accessoryView disappeared on scroll. My co-worker found pretty hack for this issue. The reason is that in iOS 7 on touchesBegan event UITableView deselects selected cell and selects touched down cell. In iOS 6 it doesnt happen and on scroll selected cell stays selected. To get same behaviour in iOS 7 try:

1) Enable multiple selection in your tableView.

2) Go to tableView delegate method didSelectRowAtIndexPath, and deselect cell touched down with code :

   NSArray *selectedRows = [tableView indexPathsForSelectedRows]; for(NSIndexPath *i in selectedRows) {     if(![i isEqual:indexPath])     {         [tableView deselectRowAtIndexPath:i animated:NO];     } } 

Fixed my problem! Hope it would be helpful, sorry for my poor English btw.

like image 91
Alexander Larionov Avatar answered Sep 28 '22 01:09

Alexander Larionov