I'm trying to center 2 or more UIView
s horizontally inside a UIView
e.g.
| [UIView1] [UIView2] |
| [UIView1] [UIView2] [UIView3] |
or
| [UIView1] [UIView2] [UIView3] [UIView4] |
I'm adding these constraints to all the views inside the container view
let horizontalConstraint = NSLayoutConstraint(item: views[N], attribute: .centerX, relatedBy: .equal, toItem: container, attribute: .centerX, multiplier: 1, constant: 0)
let verticalConstraint = NSLayoutConstraint(item: views[N], attribute: .bottom, relatedBy: .equal, toItem: container, attribute: .centerY, multiplier: 1, constant: 0)
let widthConstraint = NSLayoutConstraint(item: views[N], attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
let heightConstraint = NSLayoutConstraint(item: views[N], attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
And I'm adding a spacing constraints between each view
let spacingConstraint = NSLayoutConstraint(item: views[N], attribute: .left, relatedBy: .equal, toItem: views[N+1], attribute: .right, multiplier: 1, constant: 10)
The above constraints horizontally center all views.
If I change the priority of the horizontalConstraint
to 750 then I'm getting something like this
As you can see, when I have an odd number of views these will be horizontally aligned properly, but this is not the case when having an even number of views.
How can I center horizontally any even number of views inside and another view programmatically without using another container or spacing views?