Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select a table view cell programmatically: selectRowAtIndexPath vs setSelected

I often need to set table view cells to an initial selected state for which I use the following code:

[self.tableView selectRowAtIndexPath:indexPath 
   animated:NO scrollPosition:UITableViewScrollPositionNone];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
[cell setSelected:YES];
cell.accessoryType = UITableViewCellAccessoryCheckmark;

I am using selectRowAtIndexPath:indexPath and setSelected:YES at the same time, because I do not fully understand which of both ways are the preferred way to select a cell programmatically.

Which one of the statements should I use and why?

like image 946
AlexR Avatar asked Feb 17 '13 10:02

AlexR


1 Answers

I believe the method you want to use is selectRowAtIndexPath:animated:scrollPosition:. Usually, you should leave management of cell state to the table view. In case of selection, it stores and maintains a set of selected index paths, so the proper row will remain selected after a different cell is reused for it. There's also no need to call both methods, it is simply redundant.

like image 172
secondcitysaint Avatar answered Nov 15 '22 19:11

secondcitysaint