Uilabel Sizetofit Doesn't Work With Autolayout Ios6

UILabel sizeToFit doesn't work with autolayout ios6

Please note that in most cases Matt's solution works as expected. But if it doesn't work for you, please, read further.

To make your label automatically resize height you need to do following:

  1. Set layout constrains for label
  2. Set height constraint with low priority. It should be lower than ContentCompressionResistancePriority
  3. Set numberOfLines = 0
  4. Set ContentHuggingPriority higher than label's height priority
  5. Set preferredMaxLayoutWidth for label. That value is used by label to calculate its height

For example:

self.descriptionLabel = [[UILabel alloc] init];
self.descriptionLabel.numberOfLines = 0;
self.descriptionLabel.lineBreakMode = NSLineBreakByWordWrapping;
self.descriptionLabel.preferredMaxLayoutWidth = 200;

[self.descriptionLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setContentCompressionResistancePriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];
[self.descriptionLabel setTranslatesAutoresizingMaskIntoConstraints:NO];
[self addSubview:self.descriptionLabel];

NSArray* constrs = [NSLayoutConstraint constraintsWithVisualFormat:@"|-8-[descriptionLabel_]-8-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)];
[self addConstraints:constrs];
[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-8-[descriptionLabel_]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];
[self.descriptionLabel addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[descriptionLabel_(220@300)]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(descriptionLabel_)]];

Using Interface Builder

  1. Set up four constraints. The height constraint is mandatory.
    Sample Image

  2. Then go to the label's attributes inspector and set number of lines to 0.
    Sample Image

  3. Go to the label's size inspector and increase vertical ContentHuggingPriority and vertical ContentCompressionResistancePriority.

    Sample Image

  4. Select and edit height constraint.

    Sample Image

  5. And decrease height constraint priority.

    Sample Image

Enjoy. :)

UILabel sizeToFit only works with AutoLayout turned off

The code you've shown is fine, the problem is most likely within the constraints you have on the label within your cell (which you don't show).

Your label needs to have constraints to make it a fixed distance from each edge of its superview. This may already be the case - if so, the problem is now that the label doesn't know how to wrap its lines - you need to also set the preferredMaxLayoutWidth on the label.

I have found that tools such as DCIntrospect are really helpful when debugging Autolayout issues. For example, in this situation, its hard to tell if this is a label of the right size that is not wrapping text, or if the label is not tall enough to show your content properly.

UILabel sizeToFit and constraints

-sizeToFit should not be called if you are using auto-layout. That's part of the 'old' system.

It looks like IB has inserted explicit heights into your constraints (the vertical bars next to the labels indicate this). Try selecting the labels and hitting Cmd+= to clear these.

For multiline labels you will also need to do the following in your view controller to make everything work correctly when rotating/resizing the view:

- (void)updateLabelPreferredMaxLayoutWidthToCurrentWidth:(UILabel *)label
label.preferredMaxLayoutWidth =
[label alignmentRectForFrame:label.frame].size.width;

- (void)viewDidLayoutSubviews
[super viewDidLayoutSubviews];

[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label1];
[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label2];
[self updateLabelPreferredMaxLayoutWidthToCurrentWidth:self.label3];

[self.view layoutSubviews];

Multiline labels expose one of the weaknesses of auto-layout. We have to update preferredMaxLayoutWidth to force the label to reflow and adjust its height, otherwise if the view is resized/rotated, auto-layout does not realize the label needs to be reflowed and resized.

Calling sizeToFit() on UILabel doesn't always yield proper result in custom tableview cell

After much searching I found this thread on the topic:
UILabel sizeToFit doesn't work with autolayout ios6

It turns out that with AutoLayout, sizeToFit is not an option. So I went looking at my auto layout settings and saw that my bottom was set to equal 30px when it should be less than or equal to 30px so that the space under the text box can be expanded. Auto Layout should handle it as long as your sides have constraints or you have a width constraint, and you make your height <= some size.

Problems of constraints: sizeToFit doesn't work


According to the iOS swift the (0,0) i.e., x and y are at the top left corner of the screen. While keeping the constraints you must be careful becoz every iphone screen has its own dimensions. In order to meet those needs first of all we need to know the dimension of the screen and based upon that we can set the alignment.

For example:


were a is the height of the screen and z is the width of the screen

While doing practically add a UIview and then set constraints don't forget to add the your images or whatever may be and give them a child relationship. HAPPY CODING!!!!

UILabel sizeToFit method not working properly

Turns out the code is just fine - but the Use Autolayout was checked.
Unchecked it - everything works just great...

Autolayout programmatically with UILabel doesn't work

Add this to your code:

 noDataLabel.translatesAutoresizingMaskIntoConstraints = false

From apple documentation:

By default, the autoresizing mask on a view gives rise to
constraints that fully determine
the view's position. This allows the auto layout system to track the frames of views whose
layout is controlled manually (through -setFrame:, for example).
When you elect to position the view using auto layout by adding your own constraints,
you must set this property to NO. IB will do this for you.

Related Topics

Leave a reply