8

Using autolayout I can't override my label in code. I've set the labels attributes in IB: Lines = 0, LineBreaks = Word Wrap, but I have my height set to a single line because due to what cell is selected determines what text goes in the label. So sometimes the label will only have one line.

In my viewDidLoad:

myLabel.text = @”blah, blah, blah….”;
[myLabel setLineBreakMode:NSLineBreakByWordWrapping];
myLabel.numberOfLines  = 0; //have tried 1 but didn’t help
[myLabel sizeToFit];

This works on another project, but I wasn’t using AutoLayout. AutoLayout seems to override these settings.
I’ve even added

[myLabel setFrame:CGRectMake(20, 135, 280, 80); 

but it doesn’t help.

KFP
  • 699
  • 3
  • 12
  • 33

3 Answers3

7

Allow the intrinsic size of the label determine the height. You are correct that you need to set the numberOfLines property to 0. Since you are using AutoLayout, don't call sizeToFit and you need set the preferredMaxLayoutWidth of the label.

Justin Moser
  • 2,005
  • 3
  • 22
  • 28
4

That's because your label's properties are set only once (in viewDidLoad), while the constraints from autolayout are applied everytime your view's layoutSubviews is called.

Also, using a line break mode that wraps the text won't work well with your UILabel if it's adjusting fonts, as per Apple's docs.

If this is a UIViewController, move the UILabel override code into - (void)viewDidLayoutSubviews, or if this is in a UIView, move the code to - (void)layoutSubviews.

Don't forget to call [super viewDidLayoutSubviews] or [super layoutSubviews] in those calls.

That being said, if you see yourself needing to override your constraints, either set up the constraints and properties to what you want in the nib file, otherwise use pure code to set up your label.

Sid
  • 9,508
  • 5
  • 39
  • 60
  • I've tried this is well and it doesn't wrap the text. I use the autolayout menu to let it set up constraints in IB. If I was able to adjust the hieght of the label in code, then my other views below it will be off. – KFP Aug 05 '14 at 18:20
  • Comment referring to changing font programmatically will mess things up helped me - going to look for those Apple docs to see if I can understand exactly what is going on. – kfmfe04 Jan 06 '15 at 06:22
  • Label's properties __do need__ to be set only once, Auto Layout only changes the bounds or frame and center. – Iulian Onofrei May 23 '17 at 12:13
4

You need to set preferredMaxLayoutWidth to the maximum width your label can be. You should do this in viewWillLayoutSubviews.

Jeff Holliday
  • 760
  • 6
  • 7
  • 1
    I tried that with [super viewWillLayoutSubviews]; myLabel.preferredMaxLayoutWidth = 280; in addition to SetLineBreakMode & numberOfLines and it still doesn't wrap. – KFP Aug 05 '14 at 18:18
  • And in the case of a CollectionViewCell? – Chucky Jun 23 '21 at 09:17