简体   繁体   English

根据文本行动态调整标签大小

[英]Dynamically resize label based on lines of text

I am finding it surprisingly hard to resize a label containing newlines based on the quantity of lines and text. 我发现很难根据行和文本的数量来调整包含换行符的标签的大小。 It displays fine in a large enough textview. 它在足够大的textview中显示良好。 However, I'd like the economy of sizing the label--or I'd be happy with resizing a textview--exactly. 但是,我希望精确调整标签大小是很经济的,或者我很乐意调整文本视图的大小。

This is the code I am using from an answer on SO but it is having no effect on the size of the label. 这是我在SO答案中使用的代码,但对标签的大小没有影响。 Would appreciate any suggestions on how to make this work: 希望对如何进行这项工作提出任何建议:

NSString *list = self.list.list;
// use font information from the UILabel to calculate the size    
UITextView *view=[[UITextView alloc] initWithFrame:CGRectMake(0, 0, 280, 10)]; 
//make random size view
view.text=list;
CGSize size=[view sizeThatFits:CGSizeMake(280, CGFLOAT_MAX)];
// create a frame that is filled with the UILabel frame data
CGRect newFrame = _listLabel.frame;
// resizing the frame to calculated size
newFrame.size.height = size.height;
// put calculated frame into UILabel frame
_listLabel.frame = newFrame;

在此处输入图片说明

Why are you setting the frame of your label with reference of a newly created UITextView, it will create a useless object in your memory, to set the label frame according to your text just use this 2 line of code 为什么要参考新创建的UITextView来设置标签框架,它将在您的内存中创建一个无用的对象,只需使用以下两行代码即可根据文本设置标签框架

lbl.numberOfLines=0;
[lbl sizeToFit];

It will make the label as large as your text. 它将使标签与您的文本一样大。

You really should use autolayout. 您确实应该使用自动布局。 Just constrain the label where you need and let UIKit do it's job. 只需将标签约束在需要的地方,然后让UIKit来完成即可。

Here an example: 这里是一个例子:

I set a top space and a leading margin constraints 我设置了顶部空间和前缘限制 我设置了顶部空间和前缘限制

Then I added a width constraint and then I added some more text 然后我添加了宽度约束,然后添加了更多文本

在此处输入图片说明

As you can see the label resized itself as it knows how much text it has inside and how much space it occupies. 如您所见,标签本身会调整大小,因为它知道标签内部有多少文本以及占用了多少空间。

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

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