0

I have a table view that loads information from the web, and displays it in custom cells. In these custom cells I have a button that I assigned through storyboard.

If this button is pressed, it triggers a method (defined in the cellForRowAtIndexPath method)

cell.viewArticleButton.action = @selector(viewArticle:); 

It is in this method that I am having trouble. The action works except that it doesn't use the link provided for each respective cell (the link at each index path) instead it uses only the first row's link, regardless of what row I tap.

-(IBAction)viewArticle:(id)sender {

NSLog(@"View Article Button Tapped");

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];

NSIndexPath *indexPath = [self.tableView indexPathForCell:cell]; 

MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];

   // Open link from item.link

}

Any help would be appreciated. I have a feeling that it is this line that isn't doing what I want:

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];
Year3000
  • 459
  • 2
  • 7
  • 15

2 Answers2

1

With this line:

NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];

You are getting a reference to a prototype (or a template) cell. That won't let you uniquely identify a cell in your table view. That can only identify a group of cells that are created from this prototype cell. That is the reason why you are always getting the first row; it returns the first cell that was created using this prototype. If you only had one cell that had the identifier @"NewsCell" (other cells having different identifiers), then your implementation would work.

For uniquely identifying the cell that you have clicked, please follow these this thread: Detecting which UIButton was pressed in a UITableView.

Community
  • 1
  • 1
Guven
  • 2,280
  • 2
  • 20
  • 34
0

Why not add add in the NSIndexPath into the method:

cell.viewArticleButton.action = @selector(viewArticle:indexPath);

-(IBAction)viewArticle:(id)sender {
NSIndexPath *indexPath = (NSIndexPath *)sender;

NSLog(@"View Article Button Tapped for section %d, row $d", indexPath.section, indexPath.row);

// I have no idea why you are doing this...
NewsCell *cell = (NewsCell *)[self.tableView dequeueReusableCellWithIdentifier:@"NewsCell"];


MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];

   // Open link from item.link

}
LJ Wilson
  • 14,445
  • 5
  • 38
  • 62