Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using auto layout constraints programmatically create four UIView all with equal height and width

How can i create same view as below using auto layout constraints programmatically. I has been looking online for resource a while but i can't find any online tutorial to create and equalWidth and equalHeight constraints programmatically.

Please advise how can i set equalWidth and equalHeight programmatically to achieve layout like below.

enter image description here

like image 787
kaneyip Avatar asked Nov 30 '25 07:11

kaneyip


1 Answers

Something like this:

/*
 * ┌─┬─┐
 * │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.
}
like image 80
rintaro Avatar answered Dec 01 '25 21:12

rintaro