在-tableView期间获取tableview单元格的实际宽度:heightForRowAtIndexPath:当存在节索引时

时间:2010-09-05 18:33:20

标签: iphone uitableview

我的自定义UITableViewCells的正确高度取决于它们的宽度。不幸的是,很难知道-tableView:heightForRowAtIndexPath:中单元格的实际内容区域宽度,因为我必须使用的唯一信息是tableview。有几个因素可以改变内容宽度,因此它不等于tableView.bounds.size.width;我现在正在努力的是段指数。 (另一种情况是如果将tableview分组。)

一般来说,从tableView获取单元格内容宽度是否有好方法?

如果失败了,有没有办法获得截面索引的宽度,以便我可以从边界宽度中减去它? (我不想硬编码,因为它不能跨设备移植。)

注意:这不是Need access to the cell in the tableView:heightForRowAtIndexPath:的重复,因为那里的解决方案只是使用边界。它也不是Get tableView:heightForRowAtIndexPath: to happen after tableView:cellForRowAtIndexPath:?的重复,因为解决方案是硬编码常量(265.0),它不能跨设备移植。

2 个答案:

答案 0 :(得分:1)

这就是我的工作。它很难看,但它起作用,至少在我能找到的所有情况下都是如此。

- (CGFloat)sectionIndexWidthForSectionIndexTitles:(NSArray *)titles {
  UIFont *sectionIndexFont = [UIFont fontWithName:@"Helvetica-Bold" size:14.0f];
  CGFloat maxWidth = CGFLOAT_MIN;
  for(NSString *title in titles) {
    CGFloat titleWidth = [title sizeWithFont:sectionIndexFont].width;
    maxWidth = MAX(maxWidth, titleWidth);
  }

  CGFloat sectionIndexWidth = 0.0f;
  NSUInteger maxWidthInt = (int)maxWidth;
  switch(maxWidthInt) {
    case 0:
      sectionIndexWidth = 0.0f;
      break;
    case 11:
      sectionIndexWidth = 30.0f;
      break;
    case 12:
      sectionIndexWidth = 31.0f;
      break;
    case 14:
      sectionIndexWidth = 32.0f;
      break;
    default:
      sectionIndexWidth = 0.0f;
      break;
  }

  return sectionIndexWidth;  
}

答案 1 :(得分:0)

好的,为了节省其他人几个小时的工作....我费力地测试了各种字体和大小和边距,将它们与带有索引的实际表视图的UIView层次结构转储进行比较,得出这个方法将返回表索引的宽度,以便表视图单元格内容的边界可以计算为table_width - index_width。我将指出,附件视图通常还有另外20个像素的右侧数量。

我还发现在调用AFTER cellForRowAtIndexPath和willDisplayCell方法之前,没有正确设置cell.contentView.bounds,因此在这些调用期间尝试获取值注定会失败。它在viewDidAppear被调用时正确设置。

如果设备语言设置为非英文字母,我不知道如何计算索引宽度。

- (CGFloat) getMaxIndexViewWidth
{
    CGFloat indexMargin = 21.0;   
    NSArray *sectionTitles = [self sectionIndexTitlesForTableView:nil];  //NOTE -- if multiple tables, pass real one in

    CGFloat maxWidth11 = CGFLOAT_MIN;

    for(NSString *title in sectionTitles)
    {
        CGFloat titleWidth11 = [title sizeWithFont:[UIFont  fontWithName:@"Helvetica-Bold" size:11.0f]].width;
        maxWidth11 = MAX(maxWidth11, titleWidth11);     
    }
    return maxWidth11+indexMargin;
}