UICollectionViewCell 中的 UITableView:展开到全尺寸

UITableView inside UICollectionViewCell: expand to full size

我正在寻找一种实现布局的方法,如下所示:

本质上,它由 UICollectionViewCell 和其中的 UITableView 实例组成。 UICollectionViewCell 包含一些其他补充元素,但这些元素与此问题无关。

我想要完全展开 UITableView,即显示所有单元格。我选择了 UITableView,因为它正是我需要的样式。

问题是 UITableView 没有完全展开。从技术上讲,我希望 UITableView 的大小等于它的 contentSize

我正在使用 AutoLayout 来计算 UICollectionViewCell 大小,因此 "resizable" UITableView 会派上用场。

到目前为止,我已经尝试过使用这种方法:

import UIKit

final class FullSizeTableView: UITableView {
    override var intrinsicContentSize: CGSize {
        return contentSize
    }
}

然后在UICollectionViewCell中使用FullSizeTableView

我已经从所有 4 个边限制了 UITableView,在顶部到 UIStackView 和底部,从左到右到 ContentView

然而,结果是这样的:

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4 /// Meanwhile, Returning 4 rows in the DataSource
    }

所以,我猜,AutoLayout 似乎不符合 UITableView 的实际大小。 哪些可能是我没有考虑到的潜在陷阱?

我对 UITableView 的目标是始终完全展开并以全尺寸显示。

更新1:

滚动已被禁用

您可以计算每一行的高度,并将 tableView 的高度设置为其总和。

这里有一个简单的函数可以做到这一点(还没有测试过,所以可能需要一些调整):

func calculateTableViewContentHeight(tableView: UITableView) -> CGFloat {
    let rows = tableView.numberOfRows(inSection: 0) // adapte to your needs
    var totalHeight: CGFloat = 0
    for i in 0..<rows {
        totalHeight += tableView.rectForRow(at: IndexPath(row: i, section: 0)).height
    }
    return totalHeight
}

试试这个 -

class ContentSizedTableView: UITableView {
override var contentSize: CGSize {
    didSet{
        self.invalidateIntrinsicContentSize()
    }
}

override var intrinsicContentSize: CGSize {
    self.layoutIfNeeded()
    return contentSize
}

override func reloadData() {
    super.reloadData()
    invalidateIntrinsicContentSize()
    layoutIfNeeded()
}
}