ios - 带有 StackView 的 UITableViewCell 不能动态调整高度

标签 ios swift uitableview uikit

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

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

在我的 cellForRowAt 数据源方法中,我将单元格出列,然后调用 cell.setup() 将任意给定数量的 View 添加到单元格的堆栈 View 中。

问题是:我的单元格的大小总是调整为估计的 80p 高度。无论我向单元格的 stackView 添加多少个 View ,它都会塞满 80p 高度。在使用 cellForRowAt 数据源方法返回它之前,stackView 和单元格不会随着我插入单元格中的每个新项目而增长。

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

最佳答案

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

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

    }

}

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

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

并且您已将 Top/Leading/Trailing/Bottom 约束到单元格的内容 View ,结果如下:

enter image description here

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

关于ios - 带有 StackView 的 UITableViewCell 不能动态调整高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51272381/

相关文章:

ios - init的可选性?(coder :) vs init(coder:). 如果nil怎么办?

ios - 从类函数返回 UIViewController

ios - 在 TableView 之外配置自定义 TableViewCell?

iphone - 以最快的方式获取 facebook 好友头像 - iOS

ios - 如果不快速执行任何操作,如何重复本地通知

ios - TableViewCell 特定单元格未正确突出显示

ios - 在 Crashlytics 上的 tableView 中的 cellForRowAtIndexPath 中发生崩溃

ios - 如何获取好友的facebook id

ios - 从文本字段在 tableView 中添加新单元格

ios - 如何仅为 64 位 iOS 设备提交存档?