Nic Hubbard
Nic Hubbard

Reputation: 42139

Autolayout max width so text doesn't flow outside of screen/view

I have a UILabel that is set to Align Center X to Superview and Align Center Y to Superview. It has no width so that it can changed based on the amount of text. A small icon also needs to sit to the left of the text:

enter image description here enter image description here

enter image description here

The problem is, when too much text is added, it flows outside of the screen:

enter image description here

Even though there is a UIView that is a parent, which has leading and trailing space of 12, it still doesn't respect that parent view. The UILabel should be making the text size smaller to fit all the text, but it isn't doing this.

How can I have a centered UILabel like this but still make it have a max width so that it will not flow outside of the screen?

Upvotes: 0

Views: 125

Answers (2)

Jeff Wolski
Jeff Wolski

Reputation: 6372

You need to set the number of lines, minimum font size and adjustsFontSizeToFitWidth.

myLabel.numberOfLines = 1;
myLabel.minimumFontSize = 6;
myLabel.adjustsFontSizeToFitWidth = YES;

If there's still too much text, you either need to go multiline, clip the text, or use an ellipsis.

For multiline, set myLabel.numberOfLines = 0

To clip the text, set myLabel.clipsToBounds = YES

To truncate with an ellipsis, set myLabel.lineBreakMode = NSLineBreakByTruncatingTail

Upvotes: 0

Daniel Hall
Daniel Hall

Reputation: 13679

The UILabel won't be constrained by the parent view unless you specifically establish what those constraints should be. So by default it doesn't take the leading and trailing edges of the superview into account at all.

I would suggest adding a width constraint from the UILabel to its parent view that is of type "Less Than Or Equal" and has a constant of 0 and a multiplier of 0.85 or some other reasonable value. This will let the label become very small or even zero width, but won't let it get larger than 85% of the width of its parent view.

Upvotes: 2

Related Questions