StackView with Labels on the ends

82 views Asked by At

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.

Stack View

3

There are 3 answers

0
DonMag On BEST ANSWER

Most straightforward way...

Give your stack view these properties:

enter image description here

Constrain the stack view Top/Leading/Trailing and desired Height constraints.

Give the Left Label desired Width and Height constraints.

Constrain Right Label equal Width and Height to Left Label.

Looks like this:

enter image description here

0
son On

You can't do it directly. However, there are a few tricks to archive this layout.

  1. Add two labels, aligning them one to the left and one to the right.

enter image description here

  1. Add two labels and a space between them.

enter image description here

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.

0
Shubham Sanghavi On

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)

// Add constraints to the stack view

stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([

        stackView.topAnchor.constraint(equalTo: view.topAnchor),
        stackView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        stackView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        stackView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
    ])