SnapKit 很容易
label1.textAlignment = .left
self.view.addSubview(label1)
label1.snp.makeConstraints { (make) -> Void in
make.height.left.top.equalTo(21)
make.right. lessThanOrEqualTo(self.view).offset(-20)
}
label2.textAlignment = .left
label2.numberOfLines = 0
self.view.addSubview(label2)
label2.snp.makeConstraints { (make) -> Void in
make.left.right.equalTo(label1)
make.top.equalTo(label1.snp.bottom).offset(20)
}
在没有 SnapKit 的情况下使用自动布局
let label1 = UILabel()
label1.textAlignment = .left
self.view.addSubview(label1)
let constraintOne = NSLayoutConstraint.init(item: label1, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 20)
let constraintTwo = NSLayoutConstraint.init(item: label1, attribute: .right, relatedBy: .lessThanOrEqual, toItem: self.view, attribute: .right, multiplier: 1, constant: -20)
let constraintThree = NSLayoutConstraint.init(item: label1, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 20)
let constraintFour = NSLayoutConstraint.init(item: label1, attribute: .top, relatedBy: .greaterThanOrEqual, toItem: self.view, attribute: .top, multiplier: 1, constant: 20)
let label2 = UILabel()
label2.textAlignment = .left
label2.numberOfLines = 0
self.view.addSubview(label2)
let layoutConstraintOne = NSLayoutConstraint.init(item: label2, attribute: .left, relatedBy: .equal, toItem: label1, attribute: .left, multiplier: 1, constant: 0)
let layoutConstraintTwo = NSLayoutConstraint.init(item: label2, attribute: .right, relatedBy: .equal, toItem: label1, attribute: .right, multiplier: 1, constant: 0)
let layoutConstraintThree = NSLayoutConstraint.init(item: label2, attribute: .top, relatedBy: .equal, toItem: label1, attribute: .bottom, multiplier: 1, constant: 20)
NSLayoutConstraint.activate([constraintOne, constraintTwo, constraintThree, constraintFour,layoutConstraintOne, layoutConstraintTwo,layoutConstraintThree ])