简体   繁体   English

无法将UILabel高度调整为其文本高度

[英]Unable to fit a UILabel height to its text height

I have a custom view where I place a UIImageView and a UILabel . 我有一个自定义视图,在其中放置UIImageViewUILabel Label's text can be any size and it is dynamically set, so I have set the label's numOfLines to 0. 标签的文本可以是任意大小,并且可以动态设置,因此我将标签的numOfLines设置为0。

In addition, I am using Autolayout . 另外,我正在使用Autolayout The image view is an icon that I place to the right of the label, and I need the top edge of both the icon and the text to be aligned (not the top of the label). 图像视图是一个放置在标签右侧的图标,我需要将图标和文本的上边缘对齐(而不是标签的顶部)。 I have tried several ways to get rid of the padding between the label and its text within ( sizeToFit , sizeThatFits ) with no success, I need the height of the label to exactly match the height of the text to be able to align the top of the text with the icon... How could I achieve that? 我尝试了几种方法来摆脱标签和标签文本之间的填充( sizeToFitsizeThatFits ),但均未成功,我需要标签的高度与文本的高度完全匹配才能对齐顶部带图标的文字...我该如何实现?

If you want to set dynamic height to label in that case first you need to check prefferedmaxwidth option in storyboard/xib for that label, then set uilabel constraints. 如果要在这种情况下设置动态高度以标记,则首先需要检查情节提要/ xib中的prefferedmaxwidth选项,然后设置uilabel约束。

sequence to set constraints to label:- 1. Top 2. leading 3. trailing 设置标签约束的顺序:-1.前2.前3.后

This will raise warning if your current label height is different than required. 如果您当前的标签高度与要求的高度不同,则会发出警告。 If this is the case then select "Update Frames" option for this label. 如果是这种情况,请为此标签选择“更新框架”选项。

now set bottom constraint. 现在设置底部约束。

no need to call sizetofit method. 无需调用sizetofit方法。 Autolayout will calculate height for you 自动版式会为您计算身高

You can change the height of label by changing Label's height constraint by using following code, 您可以使用以下代码通过更改Label的高度约束来更改Label的高度,

CGSize size = [@"your text" boundingRectWithSize:CGSizeMake(label.bounds.size.width, 10000) options:(NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName : @"FontName"} context:nil].size;

labelHeightConstraint = size.height;

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

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