Word Wrap not working for UILabel

别说谁变了你拦得住时间么 提交于 2019-12-10 14:27:04

问题


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.


回答1:


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.




回答2:


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:


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



来源:https://stackoverflow.com/questions/25142777/word-wrap-not-working-for-uilabel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!