corban
corban

Reputation: 628

UITableViewCell keeps getting deselected

I have a strange problem with UITableView: My tableview shows the names of objects from which the user can select one. The value is saved. When the tableview comes up the row is selected (in cellForRowAtIndexPath). But in viewWillAppear the row is first selected and then deselected. You can see that it is first selected because of a the blue background occurs for a short time.

I have set

self.clearsSelectionOnViewWillAppear = NO;

but that does not work ether. Can someone help me out please! Thanks in advance.

Here some sample code:

#import "ECTESTTableViewController.h"

@interface ECTESTTableViewController ()

@end

@implementation ECTESTTableViewController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.clearsSelectionOnViewWillAppear = NO;

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return 8;
}

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

    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
        //        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //cell.backgroundColor = [UIColor redColor];
    }

    if (indexPath.row == 1)
    {
        //        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        NSLog(@"select %d", indexPath.row);
        cell.selected = TRUE;
    }
    else {
        //        cell.accessoryType = UITableViewCellAccessoryNone;
        cell.selected = FALSE;
    }

    cell.textLabel.text = [NSString stringWithFormat:@"row %d", indexPath.row];
    return cell;
}

@end

Upvotes: 2

Views: 761

Answers (2)

iPatel
iPatel

Reputation: 47059

Write following code

NSIndexPath *indexPath = [tableView indexPathForSelectedRow];
[tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition: UITableViewScrollPositionNone];

Upvotes: 0

Mike Pollard
Mike Pollard

Reputation: 10195

If you want to programatically select a row in a UITableView use:

- (void)selectRowAtIndexPath:(NSIndexPath *)indexPath animated:(BOOL)animated scrollPosition:(UITableViewScrollPosition)scrollPosition

Don't be setting the selected states of the cells.

Upvotes: 6

Related Questions