HelloimDarius
HelloimDarius

Reputation: 695

How to center multiple elements inside UIView

I'm trying to center multiple elements (labels and buttons) inside UIView (or UIStackView). I tried adding elements to UIStackView with Center Alignment and Distribution Fill and Spacing 10, but my elements keeps getting positioned from the left side. I tried changing centers. Still no luck.

What i'm trying to achieve:

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

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

Is there any way of achieving this without using spacers. Theoretically I maybe could use constrains, but i'm not sure it's a good 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 be doing something wrong because this is what I get (newView is red, button is blue, text label is missing) :

enter image description here

Upvotes: 1

Views: 565

Answers (1)

Nick Perkins
Nick Perkins

Reputation: 206

Create a view, center the view where you need to. Then inside that view you can insert each element and give each one a programatic NSLayoutConstraint that has a .Leading of 5 or whatever spacing you want between elements.

VIEW[ELEMENT ELEMENT ELEMENT]

The number will not matter. Look into NSLayoutConstraints and make sure you use view.addConstraints.

Upvotes: 0

Related Questions