Search code examples
iosxcode-storyboardios-autolayout

iOS Autolayout: two views of equal width and equally spaced


I am currently having difficulty with AutoLayout. I am using interface builder and am trying to place two uiview blocks of 100 * 100. I need these blocks placed in such a way that 1st block's leading to superview equals to 2nd block's trailing to superview.Further this equals to space between these two blocks and equally changes as per screen width. I have tried using stackview giving fixed width to stackview seems to be equally spaced in 4s but not on 6s.Keeping width not fixed results in greater spacing in between blocks as here .

Does it is possible to achieve this through interface builder? Great thanks for any help.


Solution

  • IB doesn't handle this very gracefully. The kludgy solution is to add "spacer" views (views that we'll add for the sake of spacing in autolayout, but which will be invisible). Just make the spacer views widths equal and then either drop these five views in a stack view or just set up horizontal constraints so the five views abut each other:

    enter image description here

    Then, just set the spacer views background to clear color, so we don't see them, and you'll have the spacing you want:

    enter image description here


    If doing this programmatically (which I know you're not doing, but just for the sake of completeness), you'd use UILayoutGuide rather than these invisible spacer views:

    let view1 = ...
    let view2 = ...
    
    let layout1 = UILayoutGuide()
    view.addLayoutGuide(layout1)
    let layout2 = UILayoutGuide()
    view.addLayoutGuide(layout2)
    let layout3 = UILayoutGuide()
    view.addLayoutGuide(layout3)
    
    let views: [String: Any] = ["view1": view1, "view2": view2, "layout1": layout1, "layout2": layout2, "layout3": layout3]
    
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[layout1][view1(==100)][layout2(==layout1)][view2(==100)][layout3(==layout1)]|", options: .alignAllCenterX, metrics: nil, views: views))
    
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view1(==100)]", options: [], metrics: nil, views: views))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view2(==100)]", options: [], metrics: nil, views: views))
    

    It's somewhat amazing that Apple still hasn't added layout guides to IB, yet.