This is magic. Say you have a table cell with controls, and you want to reuse it without keeping a reference to it explicitly in your ViewController. Do this.

Get your cell as normal, but add any selectors you need to it when it’s being created, and then tag it with the index row number of the table.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
SPTMessagePreviewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PreviewPortraitCell"];

[cell.playButton addTarget:self action:@selector(playButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
cell.playButton.tag = indexPath.row;

return cell;
}

Then, later on in your button method, dequeue it and get the same cell back.

- (IBAction)playButtonPressed:(UIButton *)sender
{
    // dequeue cell by tag and update progress bar
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
    SPTMessagePreviewTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [cell updatePlaybackSliderForPlayer:self.player];
}

This is beautiful because now you can push functionality into your cell, and call it from your ViewController.

Advertisements