Word Wrap not working for UILabel

2019-06-23 16:22发布

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.

3条回答
The star\"
2楼-- · 2019-06-23 17:02

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.

查看更多
孤傲高冷的网名
3楼-- · 2019-06-23 17:10

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.

查看更多
别忘想泡老子
4楼-- · 2019-06-23 17:22

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

查看更多
登录 后发表回答