agapitocandemor
agapitocandemor

Reputation: 744

Duplicated Rows in Table View

I know there're similar questions like this, but they don't work for me!

I'm having my rows duplicated, and the text of the UILabel gets bolder and bolder when user comes back to any tab with table views.

Here's the code of cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
CustomCell *cell = (CustomCell *)
[tableView dequeueReusableCellWithIdentifier:CellClassName];

if (cell == nil) 
{
    NSArray *topLevelItems = [cellLoader instantiateWithOwner:self options:nil];
    cell = [topLevelItems objectAtIndex:0];
}

cell.subnavName.text = [array objectAtIndex:[indexPath section]];

UIImageView *background = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"subnavigation_off.png"]];

[cell setBackgroundView:background];

background = [[UIImageView alloc] 
              initWithImage:[UIImage imageNamed:@"subnavigation_on.png"]];

cell.selectedBackgroundView = background;
[background release];

return cell;

} What can I do to avoid the text from the UILabel to be added again on my cells when user comes back to this tab from another one? I read something about use the tag, but I can't find the way to do it.

Thank you very much!

Upvotes: 0

Views: 902

Answers (1)

AliSoftware
AliSoftware

Reputation: 32681

Soooooo classic mistake.

The problem (as quite always about TableView questions here) is that you don't use the reuse mechanism of the TableViewCells correctly.

You should try to dequeue (recycle) an existing cell, and if it does not return a cell (the tableview didn't manage to recycle an old -- already allocated but not used any more -- cell) then allocate it and configure every property that will be common to all your cells (label font, adding subviews, changing colors, etc).

Then, outside of the "if" -- so whether the cell is a newly allocated one or a cell that has been recycled (from a previously allocated but no more used cell), in all cases -- fill the cell with the specific content that depends on the indexPath (text, image, etc)

Read the Table View Programming Guide in Apple documentation, and search on StackOverflow too there are a lot of questions about TableViews that all have the same issue.

Upvotes: 1

Related Questions