swift - How to center multiple elements inside UIView -


i'm trying center multiple elements (labels , buttons) inside uiview (or uistackview). tried adding elements uistackview center alignment , distribution fill , spacing 10, elements keeps getting positioned left side. tried changing centers. still no luck.

what i'm trying achieve:

[-------label--button-------] 2 elements.

[--label--button--button--] 3 elements.

is there way of achieving without using spacers. theoretically maybe use constrains, i'm not sure it's idea because of changing number of elements.

let simpleview = uiview() simpleview.addsubview(text) simpleview.addsubview(button)   let leftleading = nslayoutconstraint(item: text, attribute:     .leadingmargin, relatedby: .equal, toitem: simpleview,                     attribute: .leadingmargin, multiplier: 1.0,                     constant: 10)  let leftleading2 = nslayoutconstraint(item: button, attribute:     .leadingmargin, relatedby: .equal, toitem: simpleview,                     attribute: .leadingmargin, multiplier: 1.0,                     constant: 10)  simpleview.addconstraint(leftleading) simpleview.addconstraint(leftleading2)   simpleview.translatesautoresizingmaskintoconstraints = false simpleview.sizetofit()  newview.addsubview(simpleview)  let horizontalconstraint = nslayoutconstraint(item: simpleview, attribute: nslayoutattribute.centerx, relatedby: nslayoutrelation.equal, toitem: newview, attribute: nslayoutattribute.centerx, multiplier: 1, constant: 0) newview.addconstraint(horizontalconstraint)  let verticalconstraint = nslayoutconstraint(item: simpleview, attribute: nslayoutattribute.centery, relatedby: nslayoutrelation.equal, toitem: newview, attribute: nslayoutattribute.centery, multiplier: 1, constant: 0) newview.addconstraint(verticalconstraint) 

i must doing wrong because (newview red, button blue, text label missing) :

enter image description here

create view, center view need to. inside view can insert each element , give each 1 programatic nslayoutconstraint has .leading of 5 or whatever spacing want between elements.

view[element element element]

the number not matter. nslayoutconstraints , make sure use view.addconstraints.


Comments