Multiple reuse identifiers in a UITableView

删除回忆录丶 提交于 2019-12-08 10:42:29

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/6962411/multiple-reuse-identifiers-in-a-uitableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!