垂直 UIStackView:如何在元素之间保持相同 space 并将它们居中?

Vertical UIStackView: how to keep same space between elements and center them?

我有一个 table 视图,每个单元格都包含一个垂直 UIStackView, 我想将所有元素放在这个堆栈视图的中心,每个元素之间的间距为 8px。这是我想要实现的视觉效果:

但这是我目前得到的结果:

我试过的代码:

在 UITableView 的委托中

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell
        (0...indexPath.row).forEach { i in
            let label = UILabel()
            label.text = "Label #\(i)"
            cell.stackView.addArrangedSubview(label)
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        5
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        180
    }

TVCell

class TVCell: UITableViewCell {
    @IBOutlet weak var stackView: UIStackView!
}

我应该怎么做才能得到预期的结果?

感谢您的帮助

由于您为行使用了固定高度,因此您希望将堆栈视图在单元格中垂直居中:

堆栈视图属性:

并且,为堆栈视图提供一个固有高度 Placeholder 以避免 Interface Builder 的投诉:

请注意,您需要更改 cellForRowAt 代码...单元格被重复使用,现在您将在上下滚动时为每个单元格添加越来越多的标签.

一种方法(这是一种不好的做法,但它有助于理解您的布局问题):

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TVCell", for: indexPath) as! TVCell
    
    // remove existing labels
    cell.stackView.arrangedSubviews.forEach {
        [=10=].removeFromSuperview()
    }
    
    (0...indexPath.row).forEach { i in
        let label = UILabel()
        label.text = "Label #\(i)"
        cell.stackView.addArrangedSubview(label)
    }
    return cell
}

这是它的样子: