31

I've got a view that contains only a UILabel. This label contains multiline text. The parent has a variable width that can be resized with a pan gesture. My problem is that when I do this resizing the UILabel does not recalculate its height such that all of the content is still visible, it simply cuts it off.

I've managed to fix it with a bit of a hack but it is horribly slow to run:

- (void)layoutSubviews {

    CGSize labelSize = [self.labelDescription sizeThatFits:CGSizeMake(self.frame.size.width, FLT_MAX)];

    if (self.constraintHeight) {
        [self removeConstraint:self.constraintHeight];
    }

    self.constraintHeight = [NSLayoutConstraint constraintWithItem:self.labelDescription attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:labelSize.height];

    [self addConstraint:self.constraintHeight];

    [super layoutSubviews];
}

Shouldn't this happen automatically with autolayout?

EDIT

The structure of my view is:

UIScrollView
---> UIView
     ---> UILabel

Here are the constraints on the UIScrollView:

<NSLayoutConstraint:0x120c4860 H:|-(>=32)-[DescriptionView:0x85c81c0]   (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c48a0 H:|-(32@900)-[DescriptionView:0x85c81c0] priority:900   (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c48e0 H:[DescriptionView:0x85c81c0(<=576)]>,
<NSLayoutConstraint:0x120c4920 H:[DescriptionView:0x85c81c0]-(>=32)-|   (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x120c4960 H:[DescriptionView:0x85c81c0]-(32@900)-| priority:900   (Names: '|':UIScrollView:0x85db650 )>,
<NSLayoutConstraint:0x8301450 DescriptionView:0x85c81c0.centerX == UIScrollView:0x85db650.centerX>,

Here are the constraints on the UIView:

<NSLayoutConstraint:0x85c4580 V:|-(0)-[UILabel:0x85bc7b0]   (Names: '|':DescriptionView:0x85c81c0 )>,
<NSLayoutConstraint:0x85c45c0 H:|-(0)-[UILabel:0x85bc7b0]   (Names: '|':DescriptionView:0x85c81c0 )>,
<NSLayoutConstraint:0x85c9f80 UILabel:0x85bc7b0.trailing == DescriptionView:0x85c81c0.trailing>,
<NSLayoutConstraint:0x85c9fc0 UILabel:0x85bc7b0.centerY == DescriptionView:0x85c81c0.centerY>

The UILabel itself has no constraints on it, aside from pinning it to the edges of its parent

simon
  • 2,635
  • 4
  • 20
  • 21
  • what are your constraints on the label and the container it's in? – larsacus Oct 31 '12 at 17:57
  • Added constraints to the original post – simon Nov 01 '12 at 03:59
  • So the only constraints that you have set on your label is that it fills it's container both horizontally and vertically? Does the text cut off when the container is a specific size, or does it always cut off the text regardless how large the container it's in is? – larsacus Nov 01 '12 at 18:22
  • Yes. Its like it does the autolayout calculations, and then when you use a pan gesture to change the size of the container it doesn't recalculate the height needed to display the entire contents of the label. It cuts it off as soon as the changes to text wrapping push it off the bottom of the UILabel, the height of it never changes. – simon Nov 01 '12 at 20:47
  • How are you resizing the container in the pan gesture? – larsacus Nov 05 '12 at 17:55
  • Changing the frame directly (I'm currently only using autolayout for the area I'm having trouble with) – simon Nov 05 '12 at 21:50
  • What happens when you call `-setNeedsLayout` or `-layoutSubviews` on your container immediately after resizing the container? – larsacus Nov 05 '12 at 23:04

3 Answers3

40

Okay, I finally nailed it. The solution is to set the preferredMaxLayoutWidth in viewDidLayoutSubviews, but only after the first round of layout. You can arrange this simply by dispatching asynchronously back onto the main thread. So:

- (void)viewDidLayoutSubviews {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.theLabel.preferredMaxLayoutWidth = self.theLabel.bounds.size.width;
    });
}

That way, you don't set preferredMaxLayoutWidth until after the label's width has been properly set by its superview-related constraints.

Working example project here:

https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/ch23p673selfSizingLabel4/p565p579selfSizingLabel/ViewController.m

EDIT: Another approach! Subclass UILabel and override layoutSubviews:

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

The result is a self-sizing label - it automatically changes its height to accommodate its contents no matter how its width changes (assuming its width is changed by constraints / layout).

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • 1
    @lichen19853 note that this solution is needed only in the OP's curious situation, where a superview resizes and changes the label's width through constraints. If you change the label's width directly, e.g. by changing its width constraint in code, you can just change its `preferredMaxLayoutWidth` there and then. – matt Nov 30 '12 at 16:01
  • 2
    As far as I can tell this solution doesn't work when the parent view grows again - the labels don't expand to take up any new space available. – simon Dec 03 '12 at 23:03
  • This solution worked for me. Although instead of subclassing UILabel my custom superview has the layoutSubviews override, which then sets the preferredMaxLayoutWidth on the subview label. – danfordham Jun 18 '15 at 10:52
26

I've fixed this issue after raising a bug with Apple. The issue that multiline text requires a two-pass approach to layout and it all relies on the property preferredMaxLayoutWidth

Here is the relevant code that needs to be added to a view controller that contains a multiline label:

- (void)viewWillLayoutSubviews
{
    // Clear the preferred max layout width in case the text of the label is a single line taking less width than what would be taken from the constraints of the left and right edges to the label's superview
    [self.label setPreferredMaxLayoutWidth:0.];
}

- (void)viewDidLayoutSubviews
{
    // Now that you know what the constraints gave you for the label's width, use that for the preferredMaxLayoutWidth—so you get the correct height for the layout
    [self.label setPreferredMaxLayoutWidth:[self.label bounds].size.width];

    // And then layout again with the label's correct height.
    [self.view layoutSubviews];
}
simon
  • 2,635
  • 4
  • 20
  • 21
  • 1
    Thanks for sharing this solution - utterly unguessable! – matt Nov 21 '12 at 19:42
  • 3
    However, I've been testing this solution and I find that setting the label's preferredMaxLayoutWidth is still coming one layout cycle too late. So sometimes it fits to the text, and sometimes the last couple of words of the text are dropped from the label (it doesn't get tall enough). – matt Nov 28 '12 at 20:17
  • I used the ideas behind this to fix my auto layout issues in my UITableViewCell by adding the two methods and also this to cellForRowAtIndexPath: `[self.label setPreferredMaxLayoutWidth:[self.tableView bounds].size.width - 16];` `[self.tableView layoutSubviews];` – James C Jul 31 '15 at 16:46
3

In Xcode 6.1 for iOS 7/8, I was able to get this to work by just setting preferredMaxLayoutWidth in a setter method that's called on my view to display the text for the label. I'm guessing it was set to 0 to begin with. Example below, where self.teachPieceLabel is the label. The label is wired up with constraints alongside other labels in a view in Interface Builder.

- (void)setTeachPieceText:(NSString *)teachPieceText {
      self.teachPieceLabel.text = teachPieceText;
      [self.teachPieceLabel setPreferredMaxLayoutWidth:[self.teachPieceLabel bounds].size.width];
}
Evan R
  • 875
  • 13
  • 27