skip to Main Content

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

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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)
        ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search