Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableViewCell turns blue when scrolling

I am getting a really strange error and I can't figure out how to fix it: When I scroll around in my UITableView it will sometimes highlight a cell blue, even when I don't fully selected.

For example:
-Cell 1-
-Cell 2-
-Cell 3-
-Cell 4-
If I put my finger down on Cell 2 and scroll to Cell 4 it will leave Cell 2 highlighted, even though didSelectRowAtIndexPath: is never fired.

Any ideas?

EDIT Added code:

UITableViewCell *cell = nil;
    
    static NSString *cellId = @"StyleDefault";
    cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] 
                 initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
    }
    
    cell.textLabel.text = @"Cell One";
    cell.textLabel.textAlignment = UITextAlignmentCenter;
    [cell setAccessoryView:nil];
    
    return cell;
like image 996
Rob Avatar asked Nov 14 '22 00:11

Rob


1 Answers

FIXED IT!

My solution was two parts:

1) In cellForRowAtIndexPath: put "cell.selected = NO;", which fixes the problem of if the cell gets touched down on then goes off screen (scrolling).

UITableViewCell *cell = nil;

static NSString *cellId = @"StyleDefault";
cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] 
             initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId] autorelease];
}

cell.textLabel.text = @"Cell One";
cell.textLabel.textAlignment = UITextAlignmentCenter;
[cell setAccessoryView:nil];

//Here:
cell.selected = NO;

return cell;

2) Put "[tableView deselectRowAtIndexPath:indexPath animated:YES];" into didSelectRowAtIndexPath: instead of what I used to have "[[tableView cellForRowAtIndexPath:indexPath] setSelected:NO];" which was wrong on so many levels.

[tableView deselectRowAtIndexPath:indexPath animated:YES];

Hopefully that helps others that have this issue. Case closed.

like image 198
Rob Avatar answered Dec 21 '22 08:12

Rob