【问题标题】:Resetting custom UITableViewCell height when iPhone is rotatediPhone旋转时重置自定义UITableViewCell高度
【发布时间】:2009-05-16 13:44:56
【问题描述】:

我正在重载委托方法 -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];
}

这是应用程序在纵向时的样子:

这是应用程序在横向时的样子:

内容的上下边缘之间存在间隙。

编辑 2

通过表格框的宽度调整尺寸参数有助于解决此显示问题:

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

【问题讨论】:

    标签: iphone uitableview


    【解决方案1】:

    这不是最佳的,但最简单的解决方案是在桌子上调用-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: 是返回单元格文本的方法)

    【讨论】:

    • 我尝试了 -reloadSections:withRowAnimation: 在 -shouldAutorotateToInterfaceOrientation: 方法中,这也不起作用。
    • 如果在视图调整大小后调用,这些都可以工作。这意味着它们应该在您的 didRotateFromInterfaceOrientation 中:
    • 另外,您似乎总是返回相同的尺寸。您应该将表格的宽度输入 -sizeWithFont:constrainedToSize: 而不是使用硬编码的 CGSize
    • -didRotateFromInterfaceOrientation: 也不起作用。此外,-sizeWithFont:constrainedToSize: 中的 CGSize 参数指定最大可能大小。单元格的宽度绘制正确,但高度不正确。
    • 这似乎会导致最新 iOS 的无限循环
    猜你喜欢
    • 2011-01-29
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2020-10-13
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    相关资源
    最近更新 更多