带有StackView的UITableViewCell无法动态调整高度

Bre*_*uro 5 uitableview uikit ios swift

我有一个自定义UITableViewCell,其中包含StackView对单元格内容视图具有顶部,底部,前导和尾随约束的。

设置我tableView的高度时,我给它一个估计的高度,并将rowHeight设置为UITableViewAutomaticDimension

在我的cellForRowAt数据源方法中,我使单元出队,然后调用cell.setup()将任意给定数量的视图添加到单元的stackView中。

问题是:我的单元格始终被调整为估计的80p高度。无论我将多少个视图添加到单元的stackView中,所有视图的填充高度均为80p。我在cellForRowAt数据源方法中将其返回之前,插入到单元格中的每个新项都不会使stackView以及单元格随其增长。

我为stackView尝试了不同的分发设置,但不确定在这里做错了什么。

Don*_*Mag 8

这是在自动调整大小的表格视图单元格内向堆栈视图添加按钮的简单演示:

class StackOfButtonsTableViewCell: UITableViewCell {

    @IBOutlet var theStackView: UIStackView!

    func setup(_ numButtons: Int) -> Void {

        // cells are reused, so remove any previously created buttons
        theStackView.arrangedSubviews.forEach { $0.removeFromSuperview() }

        for i in 1...numButtons {
            let b = UIButton(type: .system)
            b.setTitle("Button \(i)", for: .normal)
            b.backgroundColor = .blue
            b.setTitleColor(.white, for: .normal)
            theStackView.addArrangedSubview(b)
        }

    }

}


class ViewController: UITableViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 100
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 6
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "StackOfButtonsTableViewCell", for: indexPath) as! StackOfButtonsTableViewCell

        cell.setup(indexPath.row + 1)

        return cell

    }

}
Run Code Online (Sandbox Code Playgroud)

假设你已经创建了一个原型单元格,它的唯一内容是一个UIStackView配置为:

Axis: Vertical
Alignment: Fill
Distribution: Equal Spacing
Spacing: 8
Run Code Online (Sandbox Code Playgroud)

并且您将顶部/前导/尾随/底部约束到单元格的内容视图,结果如下:

在此处输入图片说明

不需要任何高度计算,而且由于按钮确实具有固有大小,因此不需要对按钮设置高度限制。