Topics

#103: UIStackView in Code 🚥📐

Topics

We covered UIStackView when it was first announced, way back in Bite #16. Today we'll look at how to use it in code to build a section header view:

We'll be stacking 3 regular views: a UIImageView, then a UILabel, and finally a UIButton

Nothing special about them besides fonts/colors, so we've created them off camera.

Here's our first attempt:

stackView = UIStackView(arrangedSubviews: [imageView, label, button])

stackView.axis = .Horizontal
stackView.translatesAutoresizingMaskIntoConstraints = false

addSubview(stackView)

addConstraintsWithVFL("|[stackView]|")
addConstraintsWithVFL("V:|[stackView]|")

Like in Bite #99, we'll use Auto Layout Visual Format Language to pin the stack view's edges to its superview. Look at that, not bad for our first try!

Those views are close talkers, let's add some spacing:

stackView.spacing = 10.0

Ack! What the heck is going on here?!

Let's break it down: In the default ‘Fill' distribution mode, if views don't naturally fill the axis of the stack view, the stack view will resize one (or more) according to their hugging priority (covered in Bite #69).

We'll solve our issue by setting a low hugging priority on our label, signaling to the stack view that it be the one to stretch, not our image view.

titleLabel.setContentHuggingPriority(1, forAxis: .Horizontal)

Nice, much room-ier! Finally, let's use one more trick to make the stack view add some padding around its edges:

stackView.layoutMarginsRelativeArrangement = true
stackView.layoutMargins = UIEdgeInsetsMake(7.0, 7.0, 7.0, 7.0)

Success, matches our design perfectly! Download the project at j.mp/bite103