Is it possible to have a stack view with two labels in it, but instead of being trailing or leading aligned, the labels are aligned to the edges? Thanks.
You can’t do it directly. However, there are a few tricks to archive this layout.
Add two labels, aligning them one to the left and one to the right.
Add two labels and a space between them.
Notes: Be careful when setting content hugging priority for these views. i.e. if you want the left one always show up fully (without trimming "…"), increase its content hugging priority horizontal.
It is indeed possible to have a stack view with two labels aligned to the edges instead of being trailing or leading aligned. In this scenario, you can use the UIStackView with horizontal distribution set to fill and alignment set to fill. This configuration ensures that the labels stretch to fill the available space horizontally and align to the edges of the stack view.
// Create two labels
let firstLabel = UILabel()
firstLabel.text = "Hello Team"
let secondLabel = UILabel()
secondLabel.text = "Doing Well!"
// Create a stack view
let stackView = UIStackView(arrangedSubviews: [firstLabel, secondLabel])
// Set stack view properties
stackView.axis = .horizontal
stackView.distribution = .fill
stackView.alignment = .fill
// Add stack view to the view hierarchy
view.addSubview(stackView)
2
Answers
You can’t do it directly. However, there are a few tricks to archive this layout.
Notes: Be careful when setting
content hugging priority
for these views. i.e. if you want the left one always show up fully (without trimming "…"), increase its content hugging priority horizontal.It is indeed possible to have a stack view with two labels aligned to the edges instead of being trailing or leading aligned. In this scenario, you can use the UIStackView with horizontal distribution set to fill and alignment set to fill. This configuration ensures that the labels stretch to fill the available space horizontally and align to the edges of the stack view.
// Add constraints to the stack view