开发者

Multiple reuse identifiers in a UITableView

开发者 https://www.devze.com 2023-03-26 01:02 出处:网络
I have a t开发者_Python百科able 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

I have a t开发者_Python百科able 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;
}


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!
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号