【问题标题】:Vertical UIStackView: how to keep same space between elements and center them?垂直 UIStackView:如何在元素之间保持相同的空间并将它们居中?
【发布时间】:2021-06-04 17:01:41
【问题描述】:

我有一个表格视图,每个单元格都包含一个垂直的 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!
}

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

感谢您的帮助

【问题讨论】:

  • 尝试将标签的框架设置为它所占据的整个空间。

标签: ios swift uikit uistackview


【解决方案1】:

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

堆栈视图属性:

并且,给堆栈视图一个 Intrinsic Height 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 {
        $0.removeFromSuperview()
    }
    
    (0...indexPath.row).forEach { i in
        let label = UILabel()
        label.text = "Label #\(i)"
        cell.stackView.addArrangedSubview(label)
    }
    return cell
}

它的外观如下:

【讨论】:

    猜你喜欢
    • 2014-12-20
    • 2015-07-08
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-05
    • 2017-08-20
    相关资源
    最近更新 更多