fabersky fabersky - 1 year ago 107
iOS Question

indexPath.row returns last visible cell, and didSelectRowAtIndexPath not being called

I have an NSArray and a tableView with some buttons whose title is the string in the array at the current indexpath row

- (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexpath {

_selectedRow = indexpath.row;
static NSString *simpleTableIdentifier = @"customCell";
cell = [myTableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];

[cell.playButton setTitle:array[indexpath.row] forState: UIControlStateNormal];

return cell;


Button titles are well shown.

Now I have some mp3 files whose names are the same as the strings in the array, and I want to play the file corresponding to the selected cell.

fileToPlay = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%@", array[_selectedRow]]; ofType:@"mp3"];

What's happening here is that the file played is always the one corresponding to the last visible cell in the table.

I also have

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexpath {
_selectedRow = indexpath.row;

but If I try to print _selectedRow here, nothing appears in the log.

When I click on a cell in the table, it doesn't seem selected (it's not gray colored).

dataSource and delegate are also well connected to the tableview.


I found out that if I click on the button, it's like I'm not clicking on the selected row. if I click on the cell (outside the button), the indexPath.row is correct.

enter image description here

Answer Source

Remove the following line from the cellForRowAtIndexPath method.

 _selectedRow = indexpath.row;

You are setting the _selectedRow value each time the cellForRowAtIndexPath is called,which is when each cell is drawn and explains why the value of the last cell is being taken.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download