Reputation: 23
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:
Label one should resize width wise unless it hits a max size.
Label two should always be up against the right edge of label one
How do I set these constraints programmatically?
Upvotes: 1
Views: 1339
Reputation: 183
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)
Upvotes: 0
Reputation: 4023
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)
])
Upvotes: 0