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

Jos*_*der 13 iphone uitableview

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

通常有一种很好的方法来从tableView获取单元格内容宽度吗?

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

注意:这不是需要访问tableView中的单元格的重复:heightForRowAtIndexPath:因为解决方案只是使用边界.也不是一个get tableView:heightForRowAtIndexPath:在tableView之后发生:cellForRowAtIndexPath:?因为解决方案是硬编码一个常量(265.0),它不能跨设备移植.

Jos*_*der 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;  
}
Run Code Online (Sandbox Code Playgroud)