UIStackView • Flexbox Cheatsheet
Stacks
let view = UIStackView()
// Primary axis
view.axis = .vertical
view.axis = .horizontal
// Secondary axis alignment
view.alignment = .leading
view.alignment = .center
view.alignment = .trailing
view.alignment = .fill
// Secondary axis distribution
view.distribution = /* ... */
// Priority along primary axis
view.setContentHuggingPriority(
.defaultLow,
for: /* axis */
)
view.setContentCompressionResistancePriority(
.defaultLow,
for: /* axis */
)
.stack {
display: flex;
/* Primary axis */
flex-direction: column;
flex-direction: row;
/* Secondary axis alignment */
align-items: flex-start;
align-items: center;
align-items: flex-end;
align-items: stretch;
/* Secondary axis distribution */
justify-content: /* ... */;
/* Priority along primary axis */
flex-shrink: 1;
flex-grow: 1;
}
Example 1
Label 1
Label 2
<style>
#stack {
display: flex;
flex-direction: row; /* default */
align-items: flex-start;
}
#label1 { background: red; }
#label2 { background: orange; }
</style>
<div id="stack">
<span id="label1">Label 1</span>
<span id="label2">Label 2</span>
</div>
let view = UIStackView()
view.axis = .horizontal
view.alignment = .top
let label1 = UILabel()
label1.text = "Label 1"
label1.backgroundColor = .red
let label2 = UILabel()
label2.text = "Label 2"
label2.backgroundColor = .orange
let spacer = UIView()
view.addArrangedSubview(label1)
view.addArrangedSubview(label2)
view.addArrangedSubview(spacer)
Example 2
Label 1
Label 2
<style>
#stack {
display: flex;
flex-direction: column;
justify-content: flex-end;
align-items: stretch; /* default */
}
#label1 { background: red; }
#label2 { background: orange; }
</style>
<div id="stack">
<span id="label1">Label 1</span>
<span id="label2">Label 2</span>
</div>
let view = UIStackView()
view.axis = .vertical
view.alignment = .fill
let label1 = UILabel()
label1.text = "Label 1"
label1.backgroundColor = .red
let label2 = UILabel()
label2.text = "Label 2"
label2.backgroundColor = .orange
let spacer = UIView()
view.addArrangedSubview(spacer)
view.addArrangedSubview(label1)
view.addArrangedSubview(label2)