Search code examples
swiftautolayoutinterface-builderlayout-anchor

In Swift, how to use Layout Anchor to set multiple subviews to have the same width (no constant)?


For example, I have a parent view that contains 3 subviews. I am using Layout Anchor programatically and try to achieve following layout

|--subview 1--|--subview 2--|--subview 3--|

Each of the three subviews has equal width. In other words,

subView1.width = subView2.width = subView3.width subView1.width+subView2.width+subView3.width = parentView.width

I know I can possibly to use multiplier to set up the width for subView 1 & subView 2 as:

subView1.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, multiplier: 1/3).active = true
subView2.widthAnchor.constraintEqualToAnchor(contentView.widthAnchor, multiplier: 1/3).active = true

and subView3 can have leading anchor to be aligned with subView2's trailing anchor.

However, I saw somewhere that Interface Builder can actually assign these three widths to be equal directly (without using constant or multiplier). Is it possible to do the same with Layout Anchor programatically? And how? Thanks.


Solution

  • Here is the complete set of anchors (I've tried myself and it works):

    // Create subView1
    let subView1 = UIView()
    subView1.backgroundColor = UIColor.redColor()
    subView1.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(subView1)
    
    // Create subView2
    let subView2 = UIView()
    subView2.backgroundColor = UIColor.blueColor()
    subView2.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(subView2)
    
    // Create subView3
    let subView3 = UIView()
    subView3.backgroundColor = UIColor.greenColor()
    subView3.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(subView3)
    
    subView1.leadingAnchor.constraintEqualToAnchor(contentView.leadingAnchor).active = true
    subView1.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
    subView1.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true
    
    subView2.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
    subView2.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true
    
    subView3.topAnchor.constraintEqualToAnchor(contentView.topAnchor).active = true
    subView3.trailingAnchor.constraintEqualToAnchor(contentView.trailingAnchor).active = true
    subView3.bottomAnchor.constraintEqualToAnchor(contentView.bottomAnchor).active = true
    
    subView1.trailingAnchor.constraintEqualToAnchor(subView2.leadingAnchor).active = true
    subView2.trailingAnchor.constraintEqualToAnchor(subView3.leadingAnchor).active = true
    
    // Add equal width anchors
    subView1.widthAnchor.constraintEqualToAnchor(subView2.widthAnchor).active = true
    subView2.widthAnchor.constraintEqualToAnchor(subView3.widthAnchor).active = true
    

    Hope this helps. :)