如何使用自动布局约束以编程方式创建与下面相同的视图。我一直在网上查找资源一段时间,但我找不到任何在线教程来编程创建和equalWidth和equalHeight约束。
请告知我如何以编程方式设置equalWidth和equalHeight以实现如下布局。
答案 0 :(得分:8)
这样的事情:
/*
* ┌─┬─┐
* │1│2│
* ├─┼─┤
* │3│4│
* └─┴─┘
*/
override func viewDidLoad() {
super.viewDidLoad()
let view1 = UIView(frame: CGRectZero)
let view2 = UIView(frame: CGRectZero)
let view3 = UIView(frame: CGRectZero)
let view4 = UIView(frame: CGRectZero)
view1.backgroundColor = UIColor.yellowColor()
view2.backgroundColor = UIColor.redColor()
view3.backgroundColor = UIColor.greenColor()
view4.backgroundColor = UIColor.blueColor()
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view2.setTranslatesAutoresizingMaskIntoConstraints(false)
view3.setTranslatesAutoresizingMaskIntoConstraints(false)
view4.setTranslatesAutoresizingMaskIntoConstraints(false)
view.addSubview(view1)
view.addSubview(view2)
view.addSubview(view3)
view.addSubview(view4)
let views = ["view1":view1, "view2":view2, "view3":view3, "view4":view4]
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view1][view2(==view1)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[view3][view4(==view3)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view1][view3(==view1)]|", options: .allZeros, metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[view2][view4(==view2)]|", options: .allZeros, metrics: nil, views: views))
// Do any additional setup after loading the view, typically from a nib.
}