简体   繁体   English

Word Wrap不适用于UILabel

[英]Word Wrap not working for UILabel

Using autolayout I can't override my label in code. 使用autolayout我无法在代码中覆盖我的标签。 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. 我在IB中设置了标签属性:Lines = 0,LineBreaks = Word Wrap,但是我将我的高度设置为单行,因为选择了哪个单元格确定标签中的文本。 So sometimes the label will only have one line. 所以有时标签只有一行。

In my viewDidLoad: 在我的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。 AutoLayout seems to override these settings. AutoLayout似乎覆盖了这些设置。
I've even added 我甚至补充道

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

but it doesn't help. 但它没有帮助。

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. 您是正确的,您需要将numberOfLines属性设置为0.因为您使用的是AutoLayout,所以不要调用sizeToFit,您需要设置标签的preferredMaxLayoutWidth。

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. 这是因为您的标签属性只设置了一次(在viewDidLoad ),而每次调用视图的layoutSubviews时都会应用自动布局的约束。

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. 此外,根据Apple的文档,如果调整字体,使用包装文本的换行模式将无法与您的UILabel一起使用。

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 . 如果这是一个UIViewController ,将UILabel覆盖代码移动到- (void)viewDidLayoutSubviews ,或者如果它在UIView中,则将代码移动到- (void)layoutSubviews

Don't forget to call [super viewDidLayoutSubviews] or [super layoutSubviews] in those calls. 不要忘记在这些调用中调用[super viewDidLayoutSubviews][super layoutSubviews]

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. 话虽这么说,如果你发现自己需要覆盖你的约束,要么在nib文件中设置你想要的约束和属性,否则使用纯代码来设置你的标签。

You need to set preferredMaxLayoutWidth to the maximum width your label can be. 您需要将preferredMaxLayoutWidth设置为标签的最大宽度。 You should do this in viewWillLayoutSubviews . 您应该在viewWillLayoutSubviews执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM