3

UIKit is making me feel like extremely frustrated. I have this little piece of code in Xcode playgrounds:

    let views = [UIView(), UIView(), UIView()]

for view in views {
    view.backgroundColor = UIColor.blueColor()
    view.bounds.size = CGSize(width: 40, height: 40)
}

let stack = UIStackView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
stack.backgroundColor = UIColor.redColor()

stack.addArrangedSubview(views[0])
stack.addArrangedSubview(views[1])
stack.addArrangedSubview(views[2])

stack.axis = .Horizontal
stack.distribution = .Fill
stack.alignment = .Center
stack.spacing = 5

But no matter which distribution strategy I chose, I always end up with this.My expectation is to see three squares spread evenly in the stack. Not all of them on top of each other.

enter image description here

It seem auto layout in stack view is not laying items out properly.

But why?

Earl Grey
  • 7,426
  • 6
  • 39
  • 59
  • 1
    http://stackoverflow.com/questions/30728062/add-views-in-uistackview-programmatically – Sachin Vas Sep 29 '16 at 15:36
  • 1
    It is not duplicate guys, OP is working on Xcode Playground. – Bista Sep 29 '16 at 18:06
  • were you able to resolve the issue? – Bista Dec 20 '16 at 06:31
  • Yes. Completely counterintuitively, you MUST set up some autolayout constraints on the members views. I consider this incrediblely stupid design. Apple is presenting the stack view as a solution being one abstraction layer ABOVE autolayout. Why do I still need autolayout? I shouldn't. – Earl Grey Dec 25 '16 at 16:46

1 Answers1

0

This is how I got it working:

import UIKit

func getRandomColor() -> UIColor {
    let randomRed:CGFloat = CGFloat(drand48())
    let randomGreen:CGFloat = CGFloat(drand48())
    let randomBlue:CGFloat = CGFloat(drand48())
    return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}

let standardFrame = CGRect(x: 0, y: 0, width: 200, height: 40)
let rootView = UIView(frame: standardFrame)
rootView.backgroundColor = UIColor.blueColor()

let views = [UIView(), UIView(), UIView()]

for view in views {
    view.backgroundColor = getRandomColor()
    view.bounds.size = CGSize(width: 40, height: 40)
}

let stack = UIStackView(frame: CGRect(x: 0, y: 0, width: 200, height: 40))
stack.backgroundColor = UIColor.redColor()

stack.addArrangedSubview(views[0])
stack.addArrangedSubview(views[1])
stack.addArrangedSubview(views[2])

stack.axis = .Horizontal
stack.alignment = .Fill
stack.distribution = .FillEqually
stack.spacing = 5

rootView.addSubview(stack)
Bista
  • 7,869
  • 3
  • 27
  • 55