Autolayout Tricks - Part 1

Height adjusting UILabel with autolayout in iOS.

We all know that UILabels have intrinsic content size which allows them to adjust their height based on the content size. Which means you can add UILabel to your views, set numberOfLines to zero, set appropriate height constraint and see in action that label adjust its height to accommodate the content.

Here's how to do it,

UILabel *label = [[UILabel alloc] init];
label.numberOfLines = 0;
label.textAlignment = NSTextAlignmentCenter;
label.text = @"This is very long text\nAnd this is second line\nAll Created with Autolayout\nAnd now this is last line";
label.backgroundColor = [UIColor lightGrayColor];
[self.view addSubview:label];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-10-[lab]-10-|"                                                                    options:kNilOptions
metrics:nil views:NSDictionaryOfVariableBindings (lab)]];
[autolayoutContentView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-44-[lab(>=10)]"                                                                                 options:kNilOptions
metrics:nil views:NSDictionaryOfVariableBindings (lab)]];

Here's what you can see, we have specified that UILabel height should be >=10 which allows it to stretch as content grows.

Example :

Flexible height UILabel