[英]Vertical UIStackView: how to keep same space between elements and center them?
我有一个表格视图,每个单元格都包含一个垂直的 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
}
电视细胞
class TVCell: UITableViewCell {
@IBOutlet weak var stackView: UIStackView!
}
我应该怎么做才能得到预期的结果?
谢谢您的帮助
由于您为行使用固定高度,因此您希望在单元格中垂直居中堆栈视图:
堆栈视图属性:
并且,给堆栈视图一个 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
}
这是它的外观:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.