views:

639

answers:

4

There are 5 cells and each cell has one dynamic label. the height of cell is defined as per label content using heightForRowAtIndexPath method. Now, 3 cells are being displayed. When I scroll for next cells then cellForRowAtIndexPath is called once and In the output any one (4 OR 5) cell is displayed correctly but another has 1st cell content(repeating). Is there any solution to fix this? cellForRowAtIndexPath method should be called 2 times. I have defined sections and rows correctly.

A: 

You probably are not reusing the cells correctly. When you scroll, a previous cell is reused by the UITableView, but you don't change its contents correctly.

The code in cellForRowAtIndexPath should look similar to this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *kCustomCellID = @"CustomCellID";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCustomCellID];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kCustomCellID] autorelease];
    }

    cell.textLabel.text = [self.dataArray objectAtIndex:indexPath.row];
    cell.detailTextLabel.text = [self.dateFormatter stringFromDate:[NSDate date]];

    return cell;
}

Does your look like this?

Adam Woś
Yes, I am adding label as per indexPath using switch statement.
Brij
Could you post your `cellForRowAtIndexPath`?
Adam Woś
A: 

Hi Brij,

As you don't have a fixed size for each row, you won't be able to reuse them, except to present the same content again or some similar content.

My suggestion is to create a identifier for each row with different size.

You said that you have a switch to add the content based on the indexPath, so you should dequeue the reusable cells inside each case statement, based on its size.

vfn
A: 

The problem is that the cell is not nill so it returns same cell multiple times while scrolling. I removed the condition from cellForRowAtIndexPath method.

if (cell == nil)

Now each time, It is allocating cell and works fine.

Brij
Please bear in mind that (performance-wise) this is **the worst you could have done**.
Adam Woś
The same table view is being used multiple times with different data on different button click. Let me know what should be done in this case instead of calling viewcontroller multiple times.
Brij
A: 

Remove the judgement

if (cell == nil)

That's good.I solve my problem now.Thank you very much.