我有一个UITableView
需要通过列出类似的样式来支持内容
But the tricky part is that the amount of "Label" will vary with each cell, some may have only 4 but also up to 12. Also the "Value" can be either a single word or short phrase up to two lines(like in the image above). So I decided to use UIStackView
to help me pack and size my UILabels
used to display this. I am currently stuck at a problem when the "Label" varies in length like:
我需要“值”的前端像第一张图像一样对齐,即使“标签”的长度不同。是否存在以下行为UIStackView
这允许吗?或者有其他方法可以让我获得我需要的结果吗?
注意:每个“标签”和“值”都在一个UIStackView
,我这样做是为了对齐它们。
我也尝试过使用字符串格式,但是超过一行的“值”将包裹在标签下,而不是像我在图像中所做的那样自行包裹。
我尝试将所有“标签”放在一个中UIStackView
以及另一张中的所有“值”,一旦“值”超过一行,我就无法让它们像图像中那样对齐。
或者,如果这可能是我在某个地方犯的错误,这就是我创建的方式UIStackViews
:
var higherCount = 0
if labels.count<values.count {
higherCount = values.count
} else {
higherCount = labels.count
}
mainStackView = UIStackView(frame: CGRect(x: 0, y: 0, width: frame.width, height: frame.height))
for i in 0..<higherCount {
var height:CGFloat = 20
if (values[i] as NSString).size(attributes: [NSFontAttributeName:UIFont.systemFont(ofSize: UIFont.systemFontSize)]).width > frame.width {
height = 42
}
let stackViewToAdd = UIStackView(frame: CGRect(x: 0, y: 0, width: frame.width, height: height))
let label = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: height))
if labels.count<higherCount {
label.text = ""
} else {
label.text = labels[i]
}
label.setContentCompressionResistancePriority(1000, for: .horizontal)
label.setContentHuggingPriority(999, for: .horizontal)
stackViewToAdd.addArrangedSubview(label)
let value = UILabel(frame: CGRect(x: 0, y: 0, width: frame.width, height: height))
if values.count<higherCount {
value.text = ""
} else {
value.text = values[i]
}
value.lineBreakMode = .byWordWrapping
value.numberOfLines = 2
stackViewToAdd.addArrangedSubview(value)
mainStackView?.addArrangedSubview(stackViewToAdd)
}
mainStackView?.alignment = .fill
mainStackView?.axis = .vertical
mainStackView?.distribution = .fill