以编程方式使用自动布局约束创建四个具有相同高度和宽度的UIView

kan*_*yip 1 uiview ios autolayout swift

如何以编程方式使用自动布局约束创建与下面相同的视图.我一直在网上寻找资源一段时间,但我找不到任何在线教程来编程和equWidth和equalHeight约束编程.

请告知我如何以编程方式设置equalWidth和equalHeight以实现如下布局.

在此输入图像描述

rin*_*aro 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.
}
Run Code Online (Sandbox Code Playgroud)