user1169629
user1169629

Reputation: 467

How do I call tableView:cellForRowAtIndexPath: safely in UITableView?

I have set up a tableview with a prototype cell in storyboard. Now I want to edit the cell's subview if it is swiped, so I implemented the delegate method tableView:willBeginEditingRowAtIndexPath:. How do I get the current cell being edited from inside this method? If I use tableView:cellForRowAtIndexPath: I get a new cell, not the one I need, because subsequent calls to dequeueReusableCellWithIdentifier:forIndexPath: seem to return different objects for the same identifier and indexPath.

I can reproduce this behaviour easily with the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSLog(@"cell = %@", cell);
    cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    NSLog(@"different cell = %@", cell);
}

So when I can't use this method, how do I get the current cell that is placed at a specific indexPath? I'm using iOS 6.

Upvotes: 1

Views: 2279

Answers (3)

Nishant Tyagi
Nishant Tyagi

Reputation: 9913

Use this to acces cell and modifying it :

   NSIndexPath *indexPath = [NSIndexPath indexPathForRow:your_row inSection:your_section];
    UITableViewCell *currentCell = [you_table cellForRowAtIndexPath:indexPath];
    id anySubview = [currentCell viewWithTag:subview_tag]; // Here you can access any subview of currentcell and can modify it.

Hope it helps you.

Upvotes: 2

Mert
Mert

Reputation: 6065

It is for me also a little bit confusing. Because I do not know if its newly created or get existing one. For that case i use

- (NSArray *)visibleCells

method of UITableView. And get from that array. For determining which one is I looking for use either tag property or I add indexpath property to the cell, which are set in cellForRowAtIndexPath: method. If the cell is not in array, it is invisible anyway and will be created with cellForRowAtIndexPath: method, when user scrolls.

Upvotes: 0

Mike Pollard
Mike Pollard

Reputation: 10195

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath

on UITableView

Upvotes: 4

Related Questions