Autolayout:使用约束不等式

时间:2017-06-12 19:35:06

标签: ios swift autolayout constraints

我想仅使用约束不等式以编程方式将容器内的两个或多个视图居中。它看起来像这样:

enter image description here

我使用另一个视图对两个标签进行分组并将其centerXAnchor设置为等于superview的centerXAnchor,从而实现了此行为。我也意识到使用两个间隔视图可以实现相同的目标。问题是我的应用程序会有很多视图,所以我想尽可能少地使用子视图来节省资源

我尝试使用约束不等式(第一个标签的前导锚> =视图的前导锚和第二个标签的尾随锚< =视图的尾随锚)来居中这两个视图,但我得到的结果就是这个。

enter image description here

代码:

class TestView: UIView {

let firstLabel = UILabel()
let secondLabel = UILabel()

init() {
    super.init(frame: .zero)
    self.layer.borderColor = UIColor.gray.cgColor
    self.layer.borderWidth = 1
    setupSubviewsConstraints()
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupSubviewsConstraints() {
    self.addSubview(firstLabel)
    self.addSubview(secondLabel)

    firstLabel.layer.borderColor = UIColor.yellow.cgColor
    firstLabel.layer.borderWidth = 1
    firstLabel.text = "first"
    firstLabel.translatesAutoresizingMaskIntoConstraints = false
    firstLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
    firstLabel.leadingAnchor.constraint(greaterThanOrEqualTo: self.leadingAnchor, constant: 5).isActive = true
    firstLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5).isActive = true

    secondLabel.layer.borderColor = UIColor.blue.cgColor
    secondLabel.layer.borderWidth = 1
    secondLabel.text = "second"
    secondLabel.translatesAutoresizingMaskIntoConstraints = false
    secondLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 5).isActive = true
    secondLabel.leadingAnchor.constraint(equalTo: firstLabel.trailingAnchor, constant: 5).isActive = true
    secondLabel.trailingAnchor.constraint(lessThanOrEqualTo: self.trailingAnchor, constant: -5).isActive = true
    secondLabel.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -5).isActive = true
}

0 个答案:

没有答案