el-flor
el-flor

Reputation: 1476

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.

Upvotes: 7

Views: 10859

Answers (4)

Oscar Falmer
Oscar Falmer

Reputation: 1801

Swift 3 and 4

var widthConstraint = NSLayoutConstraint(item: label, attribute: .width, relatedBy: .lessThanOrEqual, toItem: label.superview, attribute: .width, multiplier: 1.0, constant: 0.0)
label.addConstraint(widthConstraint)

Upvotes: 0

Shirish
Shirish

Reputation: 295

Drag and resize your label to fit full width of screen, may be leave some padding from both side. Set 4 constraints : 1) height of Label. 2) Top space to UIView. 3) leading space to UIView. 4) Trailing space to UIView.

And lastly make horizontalcompressionResistense priority of Label to 1000.

Upvotes: 0

Yuchen
Yuchen

Reputation: 33036

I will add left, top, right constraints as the following:

enter image description here

In storyboard, it is simply several clicks:

  • Select your label
  • In the add constraints panel (bottom right), select the constraints you want to add

enter image description here

Upvotes: 0

Tim Bernikovich
Tim Bernikovich

Reputation: 5945

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

Upvotes: 5

Related Questions