simonbs
simonbs

Reputation: 8042

Multiple reuse identifiers in a UITableView

I have a table view where the cells have a variable height. This causes problems with having a reuse identifier but I would really like the cache for UITableViewCells that Apple gave me. Therefore I tried making a variable reuse identifier and it seems but I'm not sure if it's the right way.

Can anyone tell me if I'm handling multiple reuse identifiers right?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = [self calcCellHeight:indexPath];

    NSString *CellIdentifier = [NSString stringWithFormat:@"TextCell_%f", height];

    TextCell *textCell = (TextCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (textCell == nil) {
        textCell = [[TextCell alloc] initWithHeight:height reuseIdentifier:CellIdentifier];
    }

    return textCell;
}

Upvotes: 0

Views: 1341

Answers (2)

Micah Hainline
Micah Hainline

Reputation: 14437

The best way to do this is probably to set the height every time you get the cell, and then recalculate all the internal cell frames in that setter. Here's an example:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    float height = [self calcCellHeight:indexPath];

    TextCell *textCell = (TextCell *)[tableView dequeueReusableCellWithIdentifier: @"AlwaysTheSame"];

    if (textCell == nil) {
        textCell = [[[TextCell alloc] init] autorelease];
    }
    [textCell setHeight: height];

    return textCell;
}

Also, note you forgot your autorelease the first time through.

// TextCell
- (id) init {
  if ([super initWithStyle: UITableViewCellStyleDefault 
           reuseIdentifier: @"AlwaysTheSame"]) {
    self.myInternalStuff = [[[MyInternalStuff alloc] initWithFrame: CGRectZero] autorelease]; 
    // I don't know what size I am yet!
  }
  return self;
}

- (void) setHeight: (CGFloat) height {
  self.myInternalStuff.frame = CGRectMake(0, 0, 100, height);
  // I know what height I am now, so I can lay myself out!
}

Upvotes: 3

Caleb
Caleb

Reputation: 125007

You can do that, but if there's much variability in the height of the cells it's going to pretty much defeat the purpose of caching cells. After all, you won't save much time or memory if you have fifty different sizes of cell in your cache.

If you're going to do that, I'd suggest using an int rather than a float to construct the identifier.

Upvotes: 0

Related Questions