当 iPhone 旋转时重置自定义 UITableViewCell 的高度

5

我正在重载委托方法-tableView:heightForRowAtIndexPath:并使用-sizeWithFont:constrainedToSize:来根据单元格中的文本以编程方式设置单元格的高度:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  switch (indexPath.section) {
    case(kAboutViewOverviewSection): {
      switch (indexPath.row) {
        case(kAboutViewOverviewSectionRow): {
          NSString *text = NSLocalizedString(@"kAboutViewOverviewSectionFieldText", @"");
          CGSize s = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(280, 500)];
          return s.height + 13;
        }
        default: {
          break;
        }
      }
      break;
    }
    default: {
      break;
    }
  }
  return 44.0;
}

这在表格首次绘制时有效。但是,当我将设备的方向从纵向改为横向时,单元格高度不会改变。

我尝试在我的表视图控制器中覆盖 -shouldAutorotateToInterfaceOrientation: 方法:

- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  [self.tableView reloadData];
  return YES;
}

这应该重新加载表格数据并(可能)重绘表格单元视图。但是这没有任何效果。

是否有一种方法可以在设备旋转时强制单元格以新的高度重新绘制?

编辑:我已经尝试了以下操作,但没有效果:

- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  [self.tableView reloadData];
}

以下是应用程序在纵向方向上的外观:

Portait

以下是应用程序在横向方向上的外观:

Landscape

内容的顶部和底部之间有一个间隙。

编辑2

通过表格框架的宽度调整大小参数可以帮助解决此显示问题:

CGSize s = [text sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width,500)];
1个回答

6

虽然不太理想,但最简单的解决方法是在表格上调用-reloadData

更好的解决方案是调用-beginUpdates-deleteRowsAtIndexPaths:withRowAnimation:-insertRowsAtIndexPaths:withRowAnimation:-endUpdates,或者如果只针对3.0,可以简单地调用-reloadSections:withRowAnimation:。这将添加动画。

编辑:您还需要一个适当的tableView:heightForRowAtIndexPath:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize textSize = [[self textForRowAtIndexPath:indexPath] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake([tableView frame].size.width - 20, 500)];
    return textSize.height + 13.0f;
}

(其中textForRowAtIndexPath:是返回单元格文本的方法)

我尝试在- shouldAutorotateToInterfaceOrientation:方法中使用-reloadSections:withRowAnimation:,但这也不起作用。 - Alex Reynolds
1
此外,您似乎总是返回相同的大小。您应该将表格的宽度输入-sizeWithFont:constrainedToSize:而不是使用硬编码的CGSize。 - rpetrich
好的,通过[tableView frame].size.width设置CGSize宽度似乎有所帮助。谢谢! - Alex Reynolds
1
这似乎在最新的iOS上引起了一个无限循环。 - user317033
Mark:UITableView 已更改,需要在返回单元格之前知道单元格的大小。我已更新示例以依赖新的 textForRowAtIndexPath: 方法,该方法仅返回行的文本。 - rpetrich
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接