SeanT
SeanT

Reputation: 1791

Tapping a UITableView cell is creating a new cell

I have a table, and when I click on a cell, I want to get access to that cell so I can change some properties of that cell, but for some reason it's creating a new cell each time. I can tell this because - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier is getting called every time I tap on a cell.

Here's my code for creating the cell:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *CellIdentifier = @"AccountsCell";

    NSLog(@"AccountsTableViewController : cellForRow");

    AccountsTableViewCell *cell = (AccountsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (nil == cell)
    {

        cell = [[AccountsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    }

    [cell setCurrentAccount:[self.accounts objectAtIndex:indexPath.row]];

    cell.delegate = self;

    return cell;

}

And for selecting a cell:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    AccountsTableViewCell *cell = (AccountsTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];

}

Does anyone have any idea why this is creating a new cell each time rather than giving me a reference to the cell that was tapped?

I really appreciate any help.

Upvotes: 0

Views: 311

Answers (1)

Lyndsey Scott
Lyndsey Scott

Reputation: 37300

You're essentially creating a new AccountsTableViewCell by re-rerunning the tableView:cellForRowAtIndexPath method with the tableView and indexPath as parameters.

Instead of writing:

AccountsTableViewCell *cell = (AccountsTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];

try

AccountsTableViewCell *cell = (AccountsTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];

to get the tableView's current cell at indexPath.

Upvotes: 5

Related Questions