Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set UITableViewCell selected to YES in willDisplayCell: and the cell can't be deselected anymore

I want to pre-select some rows in a multiple selection UITableView.

I do this in tableView:willDisplayCell:forRowAtIndexPath: by simply setting [cell setSelected:YES animated:NO];.

However, for some reason this disables deselection for these rows. The embedded controls still work, and so do detail disclosure buttons.

I have uploaded a sample project here: https://github.com/leberwurstsaft/TableViewIssue where you can check out the behavior (in Viewcontroller.m lines 49-51).

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setSelected:NO animated:NO]; //   -->   setSelected:YES and the cells can't be deselected anymore...
}

What seems to be the problem?

like image 381
leberwurstsaft Avatar asked Dec 05 '22 09:12

leberwurstsaft


2 Answers

In addition to setting the cell as selected, you also need to inform the tableView that the cell is selected. Add a call to -tableView:selectRowAtIndexPath:animated:scrollPosition: to your willDisplayCell: method: and you will be able to deselect it as normal.

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (/*should be selected */) {
        [cell setSelected:YES animated:NO]; 
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    }
}

This is similar to @Ivan Loya's solution, but can be done in the same method you were already using. Be sure to use UITableViewScrollPositionNone to avoid odd scrolling behavior.

like image 156
Drew C Avatar answered Dec 06 '22 23:12

Drew C


try this in view did appear, work for me

- (void)viewDidAppear:(BOOL)animated {
    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:0 inSection:0];
    [_tableView selectRowAtIndexPath:indexPath animated:YES  scrollPosition:UITableViewScrollPositionBottom];
}

in your viewController.h add and link it to the table view

@property (weak, nonatomic) IBOutlet UITableView *tableView;

and comment the line in willDisplayCell Function

like image 36
Ivan Loya Avatar answered Dec 06 '22 23:12

Ivan Loya