如何获取UITableView的内容视图的大小?

Dav*_*vid 17 iphone uitableview

我希望在填充表格时获得UITableView内容视图的大小.有关如何做到这一点的任何建议?

Vij*_*com 62

// Allows you to perform layout before the drawing cycle happens. 
//-layoutIfNeeded forces layout early. So it will correctly return the size. 
// Like dreaming before doing.

[tableView layoutIfNeeded];


CGSize tableViewSize=tableView.contentSize;
Run Code Online (Sandbox Code Playgroud)

  • 当表的内容按动态调整大小时,这似乎不起作用. (10认同)

lam*_*bmj 5

这是一种实用方法,它很难实现.可以忽略的优势是无需打电话[tableView layoutIfNeeded].

#define CGSizesMaxWidth(sz1, sz2)             MAX((sz1).width, (sz2).width)
#define CGSizesAddHeights(sz1, sz2)           (sz1).height + (sz2).height

+ (CGSize)sizeForTableView:(UITableView *)tableView {
    CGSize tableViewSize = CGSizeMake(0, 0);
    NSInteger numberOfSections = [tableView numberOfSections];
    for (NSInteger section = 0; section < numberOfSections; section++) {
        // Factor in the size of the section header
        CGRect rect = [tableView rectForHeaderInSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));

        // Factor in the size of the section
        rect = [tableView rectForSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));

        // Factor in the size of the footer
        rect = [tableView rectForFooterInSection:section];
        tableViewSize = CGSizeMake(CGSizesMaxWidth(tableViewSize, rect.size), CGSizesAddHeights(tableViewSize, rect.size));
    }
    return tableViewSize;
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*ros 5

对于高度由其单元格内容动态调整大小的表格视图 -

MytableView包含在 a 中UIView,其updateConstraints()函数如下所示:

override func updateConstraints() {
    self.tableView.layoutIfNeeded()
    self.tableViewHeight.constant = min(300, self.tableView.contentSize.height)
    super.updateConstraints()
}
Run Code Online (Sandbox Code Playgroud)

tableViewHeightIBOutlet表视图的 XIB 指定高度的一个。我得到较小的 -300 点,或表格视图内容大小的高度。


drf*_*ear 5

我不知道有多少人会喜欢这个答案,因为我不确定我是否喜欢它。但我设法得到了一些与此相关的东西。

这适用于动态高度单元。当 tableview 计算出其 contentView 时,回调将被调用几次

class ContentSizeNotifyingTableView: UITableView {
    var contentSizeDidChange: ((CGSize) -> ())?

    override var contentSize: CGSize {
        didSet {
          self.contentSizeDidChange?(self.contentSize)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)