Reputation: 1724
I have the following code to set up a UILabel:
let label = UILabel()
label.numberOfLines = 0
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.preferredMaxLayoutWidth = maxWidth
label.text = "String that is long enough to cause word wrap."
label.sizeToFit()
self.view.addSubview(label)
The result that I need is for the label to wrap the text as it would once it reaches label.preferredMaxLayoutWidth
then actually size itself to just wide enough to fit the wrapped text. Here's a diagram to illustrate:
The red box's width is equal to label.preferredMaxLayoutWidth
and that is the actual size I am getting with my code above.
The black box is the size that I would like it to be.
Whether the label was sized to the red or black, the word wrapping would be the same.
So, how can I resize my label to be the smallest possible width while maintaining the current word wrap?
Edit:
Although constraints might be the usual option, in my case, I don't think it is because I am sizing my superview according to the resulting size of this label.
Upvotes: 1
Views: 1892
Reputation: 1724
Ok, I just figured it out. @rmaddy was correct in the question's comments above. I had seen boundingRectWithSize:options:attributes:context:
before asking the question, but had issues figuring it out in swift. But now I've got it. Here is my updated code:
let label = UILabel()
let text = "String that is long enough to cause word wrap."
let rect = text.boundingRect(with: CGSize(width: maxDesiredWidth, height:CGFloat.greatestFiniteMagnitude), options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: nil, context: nil)
label.numberOfLines = 0
label.textAlignment = .center
label.lineBreakMode = .byWordWrapping
label.frame = rect
label.text = text
label.sizeToFit()
self.view.addSubview(label)
Upvotes: 2