Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
410 views
in Technique[技术] by (71.8m points)

ios - Constraints for dynamically size uilabel width programmatically

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?

question from:https://stackoverflow.com/questions/65557693/constraints-for-dynamically-size-uilabel-width-programmatically

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...