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

时间:2018-07-10 19:01:12

标签: ios swift uitableview uikit

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

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

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

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

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

2 个答案:

答案 0 :(得分:3)

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

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

    }

}

假设您已经创建了一个原型单元,并且其唯一内容是配置为:{p}的UIStackView

Axis: Vertical
Alignment: Fill
Distribution: Equal Spacing
Spacing: 8

并将其限制在单元格的内容视图的顶部/顶部/底部/底部,这是结果:

enter image description here

不需要任何高度计算,并且由于按钮 do 具有固有大小,因此无需在按钮上设置高度限制。

答案 1 :(得分:-1)

这里有一个例子,它是一个tableView,它使用一个包含stackView的单元格,并且从nib文件中获取在stackView中加载的视图

https://github.com/Joule87/stackView-within-TableViewCell