@benguild: The official homepage of Ben Guild.

Fixing AutoLayout on UILabel(s) in iOS Development

15 Jul 2014  |  Tags: ,

AutoLayout is a really quick way to create responsive layouts on iOS 6, 7, and higher / Mac OS(es). However, I found that there's a really stupid problem with UILabel(s) in getting them to act like actual paragraphs that resize themselves to their own contents. They often don't do that properly using just AutoLayout constraints....

Oddly enough, calling “[label sizeToFit]” manually can band-aid the issue, but then hose the rest of your AutoLayout in some instances. — So what's wrong? Isn't AutoLayout supposed to “compress” UILabel(s) to their minimum required size based on their assigned constraints?

iOS AutoLayout UILabel Bug demonstrated (graphically)
As you can see, without this fix the pink-colored label is taller in the same context when the view is loaded on a larger screen.

The tricky thing about UILabel(s) is that they generally will actually resize themselves, but this doesn't always work predictably due to this bug in UIKit. On iPads, you might end up with taller labels… where as on a 3.5-inch iPhone they might look just fine with the display oriented vertically and then grow taller when rotated horizontally.

The easiest solution to this behavior is to subclass UILabel and add this little gem to force the “PreferredMaxLayoutWidth” on the label to reset automatically whenever the view is resized. This makes its width 100% of its container's width (as it most likely should be), and leaves only its height to be adjusted dynamically by whatever the UILabel's content and AutoLayout constraints actually should negotiate between themselves:

- (void)layoutSubviews {
    self.preferredMaxLayoutWidth = self.bounds.size.width;
    [super layoutSubviews];

This approach not only keeps your code clean but also keeps the issue isolated. One can now rely almost solely on AutoLayout for controlling text and content variations amongst varying localizations and differing device resolutions or aspect ratios. (… and in the least annoying way possible!)

Comments are in a testing stage. Enabled since 2013/09/09.