fabdurso
fabdurso

Reputation: 2444

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.

UPDATE

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.

Upvotes: 1

Views: 308

Answers (3)

Bhadresh Kathiriya
Bhadresh Kathiriya

Reputation: 3244

Set Code:

 - (CustomCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexpath {
 cell.playButton.tag = indexpath.row;
[cell.playButton addTarget:self action:@selector(btnPlay:) forControlEvents:UIControlEventTouchUpInside];
}
- (IBAction)btnPlay:(id)sender{
    UIButton *btn = (UIButton *)sender;
    _selectedRow = btn.tag;
}

You are select selection color for touch color set. enter image description here

Upvotes: 1

Ruchira Randana
Ruchira Randana

Reputation: 4179

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.

Upvotes: 3

Akshansh Thakur
Akshansh Thakur

Reputation: 5331

Try these:

1) set myGestureRecognizer.cancelsTouchInView to false... maybe your touches are getting in way. (It's a common issue when you may have gesture recognizers)

2) In your tableView's attribute's inspector, set Selection to singleton. That solved my issue

3) set this : [tableView setAllowsSelection:YES];

Upvotes: 0

Related Questions