我是iOS开发的新手,我对如何实现这一目标感到困惑。
我向UILabel
中添加了2个UIStackView
,如下所示:
let horizontalStackView1 = UIStackView(arrangedSubviews: [self.label1, self.label2])
当我运行应用程序时,它看起来像这样:
我曾经尝试设置horizontalStackView1.distribution
,horizontalStackView1.alignment
等,但是没有运气。
我该如何实现?
谢谢!
更新:
代码看起来像这样(顺便说一下,它是一个表格的单元格):
class ItemTableViewCell: UITableViewCell
{
...
let stateLabel = UILabel()
let effectiveDateLabel = UILabel()
...
var typeImage: UIImage?
{
...
}
var summary: String?
{
...
}
var effectiveDate: Date?
{
...
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?)
{
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.accessoryType = .disclosureIndicator
...
let horizontalStackView1 = UIStackView(arrangedSubviews: [self.stateLabel, self.effectiveDateLabel])
let horizontalStackView2 = UIStackView(arrangedSubviews: [typeImageViewWrapper, self.titleLabel])
horizontalStackView2.spacing = 4
let verticalStackView = UIStackView(arrangedSubviews: [horizontalStackView1, horizontalStackView2, self.summaryLabel])
verticalStackView.axis = .vertical
verticalStackView.spacing = 4
self.contentView.addSubview(verticalStackView)
...
}
required init?(coder aDecoder: NSCoder)
{
fatalError()
}
}
答案 0 :(得分:3)
这是因为UIStackView会选择第一个具有最低内容拥护优先级的ArrangedSubview并调整其大小,以便Stackview的内容占据全宽。
如果要在这种情况下使用UIStackView,则可以更改包含优先级的内容,例如。
label2.setContentHuggingPriority(.defaultLow, for: .horizontal)
label1.setContentHuggingPriority(.defaultHigh, for: .horizontal)