Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - set maximum width for UILabel with Autolayout

I have a UILabel contained in a UIView that has a fixed size. The UILabel has dynamic text. How can I make sure that the UILabel will never get bigger than the containing UIView?

Before using AutoLayout this was quite simple to achieve by simply using the AdjustsFontSizeToFitWidth, but I can't manage to get this working with Autolayout anymore.

What contraints should I add from the UILabel to the UIView? Right now it is simply Leading aligned.

like image 709
el-flor Avatar asked Dec 04 '15 12:12

el-flor


1 Answers

There are special methods for such views like UILabel (contentHugging and contentCompressionResistance), but they are already enabled. So all you need to disable label's width grow to superview's width.

NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:self.label attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationLessThanOrEqual toItem:self.label.superview attribute:NSLayoutAttributeWidth multiplier:1.0f constant:0.0f];    
[self.label addConstraint:widthConstraint];
like image 194
Timur Bernikovich Avatar answered Oct 08 '22 18:10

Timur Bernikovich