UIStackView-强制标签变紧并使其尽可能宽

时间:2019-01-12 09:41:06

标签: swift uistackview

我有UIStackView

let sv = UIStackView()
sv.axis = .horizontal
sv.distribution = .fillProportionally
sv.spacing   = 2.0
sv.translatesAutoresizingMaskIntoConstraints = false

现在,我添加了两个元素(UIView和UILabel)。如果我运行应用程序,则会看到类似以下的内容:

| Content (UIView)|           Content (UILabel)|

但是我想要这样:

| Content (UIView)           | Content (UILabel)|

该怎么做?

我用于设置堆栈视图的代码:

let lb = UILabel()
lb.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.light)
lb.lineBreakMode = .byTruncatingTail
lb.numberOfLines = 2
lb.textAlignment = .right
lb.backgroundColor = UIColor.red
lb.adjustsFontSizeToFitWidth = true


let v = UIView()


stackView.addArrangedSubview(v)
stackView.addArrangedSubview(lb)
self.contentView.addSubview(stackView)


NSLayoutConstraint.activate([
   stackView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 2),
   stackView.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10),
   stackView.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10),
   stackView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -2)
])   

1 个答案:

答案 0 :(得分:0)

只需将视图的水平轴的内容压缩阻力优先级设置为1000

v.setContentCompressionResistancePriority(.required, for: .horizontal)

...那么您的视图应该占用所需的空间,因为它不会被压缩