skip to Main Content

I have two labels set completely programmatically. Label two should always be up against the right edge of label one (with a small space between them). Label one has its width set to be equal to its content size unless it hits a max width. Visually:

|Label one| |Label two|

I need the following constraints:

  1. Label one should resize width wise unless it hits a max size.

  2. Label two should always be up against the right edge of label one

How do I set these constraints programmatically?

2

Answers


  1. lessThanOrEqualToConstant for the widthAnchor should do the job.

    let labelOne = UILabel()
    labelOne.text = "label1"
    let labelTwo = UILabel()
    labelTwo.text = "label2"
    
    labelOne.translatesAutoresizingMaskIntoConstraints = false
    labelTwo.translatesAutoresizingMaskIntoConstraints = false
    
    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    
    NSLayoutConstraint.activate([
        labelOne.topAnchor.constraint(equalTo: view.topAnchor),
        labelOne.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        labelOne.widthAnchor.constraint(lessThanOrEqualToConstant: 100),
        
        labelTwo.leadingAnchor.constraint(equalToSystemSpacingAfter: labelOne.trailingAnchor, multiplier: 1),
        labelTwo.topAnchor.constraint(equalTo: view.topAnchor)
    ])
    
    Login or Signup to reply.
  2. I agree with @Kevvv answer but you have to also assign trailing constraint of labelTwo to view’s trailing, because if labelTwo width will increase if content size is more.

    just add one or more constraint

    labeltwo.trailingAnchor.constraint(greaterThanOrEqualTo: view.trailingAnchor)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search