UICollectionViewCell内的UITableView:展开为完整大小

问题描述 投票:4回答:1

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

layout example

基本上,它由UICollectionViewCell组成,其中包含UITableView的实例。 UICollectionViewCell包含少量其他补充元素,但与该问题无关。

我希望UITableView被完全展开,即显示所有单元格。我选择了UITableView,因为它恰好具有我需要的样式。

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

我正在使用自动布局来计算UICollectionViewCell大小,因此“可调整大小的” UITableView会派上用场。

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

import UIKit

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

然后使用FullSizeTableView中的UICollectionViewCellenter image description here

我已将UITableView从四个侧面全部约束,从顶部到UIStackView以及从底部,左,右到ContentView

但是,结果看起来像这样:

incorrect result

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

因此,我想AutoLayout似乎并不尊重UITableView的实际大小。我没有考虑的潜在陷阱是什么?

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

Update1:​​

已禁用滚动enter image description here

ios swift uitableview autolayout uicollectionviewcell
1个回答
0
投票

您可以计算每行的高度,并将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
}
© www.soinside.com 2019 - 2024. All rights reserved.