【问题标题】:UITableView content heightUITableView 内容高度
【发布时间】:2011-12-09 16:58:05
【问题描述】:

我有一个设置为不启用滚动的 UITableView,它存在于 UIScrollView 中。我这样做是因为设计规范要求看起来像表格视图的东西(实际上有两个并排),并且实现表格视图而不是添加一大堆按钮会容易得多,(分组表视图)。

问题是,我需要知道滚动视图的容器视图有多大,所以它会滚动表格视图的整个高度。加载后,有什么方法可以找到 tableview 的高度?没有像滚动视图这样的 contentView 属性,框架似乎是静态的,等等......

有什么想法吗?

【问题讨论】:

  • 这里的情况相同。

标签: uitableview height


【解决方案1】:

使用

CGRect lastRowRect= [tableView rectForRowAtIndexPath:index_path_for_your_last_row];
CGFloat contentHeight = lastRowRect.origin.y + lastRowRect.size.height;

然后您可以使用 contentHeight 变量来设置滚动视图的 contentSize。

【讨论】:

  • 似乎不适用于带有自动调整单元格的表格。
【解决方案2】:

对我有用的更通用的解决方案:

CGFloat tableViewHeight(UITableView *tableView) {
    NSInteger lastSection = tableView.numberOfSections - 1;
    while (lastSection >= 0 && [tableView numberOfRowsInSection:lastSection] <= 0)
        lastSection--;
    if (lastSection < 0)
        return 0;
    CGRect lastFooterRect = [tableView rectForFooterInSection:lastSection];
    return lastFooterRect.origin.y + lastFooterRect.size.height;
}

除了 Andrei 的解决方案之外,它还考虑了空白部分和部分页脚。

【讨论】:

    【解决方案3】:

    UITableViewUIScrollView 的子类,所以它有一个contentSize 属性,你应该可以毫无问题地使用它:

    CGFloat tableViewContentHeight = tableView.contentSize.height;
    scrollView.contentSize = CGSizeMake(scrollView.contentSize.width, tableViewContentHeight);
    

    但是,正如several other SO 问题所指出的那样,当您更新表格视图(如插入一行)时,它的contentSize 似乎不会像它那样立即更新UIKit 中的大多数其他动画调整大小。在这种情况下,您可能需要求助于 Michael Manner 的回答。 (虽然我认为在UITableView 上实现一个类别更有意义)

    【讨论】:

      【解决方案4】:

      您可以遍历这些部分并使用rectForSection 来计算总高度(这也包括页脚和页眉!)。迅速我在UITableView上使用以下扩展名

      extension UITableView {
          /**
           Calculates the total height of the tableView that is required if you ware to display all the sections, rows, footers, headers...
           */
          func contentHeight() -> CGFloat {
              var height = CGFloat(0)
              for sectionIndex in 0..<numberOfSections {
                  height += rectForSection(sectionIndex).size.height
              }
              return height
          }
      
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-28
        • 2021-12-12
        • 1970-01-01
        • 1970-01-01
        • 2017-02-16
        • 2010-10-19
        • 2022-01-22
        • 2016-01-20
        • 2012-05-04
        相关资源
        最近更新 更多