Tom Fobear
Tom Fobear

Reputation: 6749

UITableView and indexPathsForSelectedRows

I have a tableView that I have set allowsMultipleSelection to YES in storyboard.

EDIT

I was wrong about one thing... [tableView indexPathsForSelectedRows] does return a NSArray with 1 object in it during didSelectRowAtIndexPath.

However it does not work in cellForRowAtIndexPath after I reload the table so it will check which accessory (check mark or not) to apply.

In the original question I was trying to manually select the rows... Apparently that is handled by the tableView itself.. but somewhere along the way it is automatically deselecting my row as I never call deselectRowAtIndexPath on it...

Original Question:

For some reason when I set the cell to selected it does not change.

- (void)tableView:(UITableView *)tableView 
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

    //cell does not update selected property to YES after this next line
    cell.selected = YES;

    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]  
               withRowAnimation:UITableViewRowAnimationFade];
}

I suppose I can keep track of the selected index paths myself... but I can swear I used a method that involved indexPathsForSelectedRows previously with success...

Upvotes: 3

Views: 5412

Answers (4)

Tom Fobear
Tom Fobear

Reputation: 6749

A bit unfair since the question changed but.. for me.. the answer is either don't use

indexPathsForSelectedRows

or don't call

reloadTable

on your tableView.

I opted for the later, I decorated the accessory in didSelectRow and didDeselectRow instead of doing it on reload and just never reloading the table.

If someone can come up with a solution that involves both of the above, I will select that answer instead.

Upvotes: 0

jason
jason

Reputation: 98

please post your all codes for this class in pastbean and put your link here we need more information,

and also try:

//in your interface

 @interface YourClass (){
 NSInteger _selectedIndex;
 }

// cellForRowAtIndexPath: method

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath  
 *)indexPath
 {
 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

// didSelectRowAtIndexPath: method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
_selectedIndex = indexPath.row;
[self.tableView reloadData];

}

Upvotes: 1

PaulG
PaulG

Reputation: 7102

Try [cell setSelected:YES animated:YES]

I'm pretty sure cell.selected is read only

Upvotes: 1

Omar Abdelhafith
Omar Abdelhafith

Reputation: 21221

You cannot set the selected property directly

So instead of

cell.selected = YES;

Use

[tableView selectRowAtIndexPath:TheIndexPAth animated:YES scrollPosition:UITableViewScrollPositionBottom];

Upvotes: 2

Related Questions