6

I'd like to align the Blue and Purple views to the center of the screen, and I'd like to align the green view to the left of the screen:

enter image description here

Here is my code:

view.backgroundColor = UIColor.orangeColor()

//Stackview: 
let stackView   = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
self.view.addSubview(stackView)

stackView.topAnchor.constraintEqualToAnchor(self.view.topAnchor).active = true
stackView.leftAnchor.constraintEqualToAnchor(self.view.leftAnchor).active = true
stackView.rightAnchor.constraintEqualToAnchor(self.view.rightAnchor).active = true

stackView.axis  = UILayoutConstraintAxis.Vertical
stackView.alignment = .Center

//Blue view: 
let blueBox = UIView()
stackView.addArrangedSubview(blueBox)
blueBox.backgroundColor = UIColor.blueColor()
blueBox.heightAnchor.constraintEqualToConstant(140).active = true
blueBox.widthAnchor.constraintEqualToConstant(140).active = true

//Inner stackview that contains the green view: 
let greenBoxContainer = UIStackView()
let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)
greenBoxContainer.alignment = .Leading

//Green view:
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true

//Purple view: 
let purpleView = UIView()
stackView.addArrangedSubview(purpleView)
purpleView.backgroundColor = UIColor.purpleColor()
purpleView.heightAnchor.constraintEqualToConstant(50.0).active = true
purpleView.widthAnchor.constraintEqualToConstant(50.0).active = true

To repeat, how can I align the left edge of the green view with the left edge of the screen?

I tried this:

greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true

but it only stretches the green view through the length of the screen.

Eric
  • 16,003
  • 15
  • 87
  • 139

1 Answers1

1

One way is to add a spacer view:

let greenBox = UIView()
stackView.addArrangedSubview(greenBoxContainer)
greenBoxContainer.addArrangedSubview(greenBox)

let spacer = UIView()
greenBoxContainer.addArrangedSubview(spacer)
spacer.rightAnchor.constraintEqualToAnchor(greenBoxContainer.rightAnchor).active = true

greenBoxContainer.widthAnchor.constraintEqualToAnchor(stackView.widthAnchor).active = true
greenBox.backgroundColor = UIColor.greenColor()
greenBox.widthAnchor.constraintEqualToConstant(120).active = true
greenBox.heightAnchor.constraintEqualToConstant(120).active = true

Note that I'm no longer setting greenBoxContainer's alignment, so it defaults to .Fill. Thus the right edge of spacer is flushed to the inner stackview's right edge, and it takes up all the width, leaving greenBox just enough room to satisfy its width constraint.

But this is a workaround, I'd like to be able to specify alignments without having to create spacer views..

Eric
  • 16,003
  • 15
  • 87
  • 139