ios UILabel 根据要显示的文本自动调整大小

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5430890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 19:22:18  来源:igfitidea点击:

UILabel auto resize on basis of text to be shown

iosobjective-cuilabeluitextview

提问by Muhammad Uzair Arshad

I'm working on an application, in which I'm required to autoresize the text area on basis of text to be displayed.

我正在开发一个应用程序,其中我需要根据要显示的文本自动调整文本区域的大小。

Firstly, I'm not sure for this either I should use UILabel(Logically is the best choice for displaying static text, which is in my case) or UITextView.

首先,我不确定我应该使用UILabel(逻辑上是显示静态文本的最佳选择,就我而言)或UITextView.

How I wish to use it?
I want to simply init my Label or text view for that matter with Text. Instead I define the frame first and then restrict my text in that area.

我希望如何使用它?
我想简单地使用文本初始化我的标签或文本视图。相反,我首先定义框架,然后限制该区域中的文本。

If you can suggest the right solution, that will be a great help.

如果你能提出正确的解决方案,那将是一个很大的帮助。

I went through documentation and other references but didn't find much which could help me here or I could've overlooked it.

我浏览了文档和其他参考资料,但没有找到太多可以帮助我的地方,或者我可能忽略了它。

回答by Muhammad Uzair Arshad

The sizeToFitmethod worked just great.

sizeToFit方法效果很好。

I did following.

我做了以下。

UILabel *testLabel =[[UILabel alloc] initWithFrame:CGRectMake(6,3, 262,20 )]; // RectMake(xPos,yPos,Max Width I want, is just a container value);

NSString * test=@"this is test this is test inthis is test ininthis is test inthis is test inthis is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...this is test in uilabel ...";

testLabel.text = test;
testLabel.numberOfLines = 0; //will wrap text in new line
[testLabel sizeToFit];

[self.view addSubview:testLabel];

回答by j_freyre

You can find a text size with :

您可以使用以下命令找到文本大小:

CGSize textSize = [[myObject getALongText] 
                    sizeWithFont:[UIFont boldSystemFontOfSize:15] 
                    constrainedToSize:CGSizeMake(maxWidth, 2000)
                    lineBreakMode:UILineBreakModeWordWrap];

then you can create your UILabellike that :

然后你可以创建你UILabel喜欢的:

UILabel * lbl = [[UILabel alloc] initWithFrame:CGRectMake(0,0,textSize.width, textSize.height];
[lbl setNumberOfLines:0];
[lbl setLineBreakMode:UILineBreakModeWordWrap];
[lbl setText:[myObject getALongText]];

回答by Segev

In Swift:

在斯威夫特:

testLabel = UILabel(frame: CGRectMake(6, 3, 262, 20))
testLabel.text = test
testLabel.numberOfLines = 0
testLabel.sizeToFit()

In Objective C

在目标 C

UILabel *testLabel = [[UILabel alloc] initWithFrame: CGRectMake(6, 3, 262, 20)]];
testLabel.text = test;
testLabel.numberOfLines = 0;
[testLabel sizeToFit];

回答by Berik

If you want to resize the UILabel only in height, use this:

如果您只想在高度上调整 UILabel 的大小,请使用以下命令:

@property (nonatomic, weak) IBOutlet UILabel *titleLabel;

CGRect titleLabelBounds = self.titleLabel.bounds;
titleLabelBounds.size.height = CGFLOAT_MAX;
// Change limitedToNumberOfLines to your preferred limit (0 for no limit)
CGRect minimumTextRect = [self.titleLabel textRectForBounds:titleLabelBounds limitedToNumberOfLines:2];

CGFloat titleLabelHeightDelta = minimumTextRect.size.height - self.titleLabel.frame.size.height;
CGRect titleFrame = self.titleLabel.frame;
titleFrame.size.height += titleLabelHeightDelta;
self.titleLabel.frame = titleFrame;

Now you can use titleLabelHeightDeltato layout other views depending on your label size (without using autolayout).

现在,您可以titleLabelHeightDelta根据标签大小来布局其他视图(不使用自动布局)。

回答by Erik Tjernlund

I'm not sure I totally understand the question, but you can use the sizeToFitmethod on a UILabel(the method is inherited from UIView) to change the size according to the label text.

我不确定我是否完全理解这个问题,但是您可以使用sizeToFita 上UILabel的方法(该方法继承自UIView)根据标签文本更改大小。

回答by Anand

The easiest way to find the no. of lines depending on text. You can use this code:

查找编号的最简单方法。取决于文本的行数。您可以使用此代码:

ceil(([aText sizeWithFont:aFont].width)/self.bounds.size.width-300); 

it returns some float value.

它返回一些浮点值。

[lbl setNumberOfLines:floatvalue];

回答by Ilja Popov

Please note that with autolayout call sizeToFit won't change size, because it will be changed later by autolayout calculations. In this case you need to setup proper height constraint for your UILabel with "height >= xx" value.

请注意,使用自动布局调用 sizeToFit 不会更改大小,因为稍后会通过自动布局计算进行更改。在这种情况下,您需要使用“height >= xx”值为 UILabel 设置适当的高度约束。

回答by Alex

Because you're going to use this solution countless times in your app, do the following:

因为您将在您的应用程序中无数次使用此解决方案,请执行以下操作:

1) Create a directory called extensionsand add a new file inside called UILabel.swiftwith the following code:

1)创建一个名为目录extensions,并添加新的文件中调用UILabel.swift下面的代码:

import UIKit

extension UILabel {
    func resizeToText() {
        self.numberOfLines = 0
        self.sizeToFit()
    }
}

2) In your app code, define the label width you want and just call resizeToText():

2)在您的应用程序代码中,宽度你想,只是调用定义标签resizeToText()

label.frame.size.width = labelWidth
label.resizeToText()

This will maintain width while increasing the height automatically.

这将保持宽度,同时自动增加高度。

回答by Patel Jigar

try bellow code, it works for multiline

试试下面的代码,它适用于多行

self.labelText.text = string;
self.labelText.lineBreakMode = NSLineBreakByWordWrapping;
self.labelText.numberOfLines = 0;

回答by MARK IOS Developer

You can change the size of label based on length of the string by, using this function

您可以使用此函数根据字符串的长度更改标签的大小

func ChangeSizeOfLabel(text:String) -> CGSize{

    let font = UIFont(name: "HelveticaNeue", size: 12)!
    let textAttributes = [NSFontAttributeName: font]
    let size = text.boundingRectWithSize(CGSizeMake(310, 999), options: .UsesLineFragmentOrigin, attributes: textAttributes, context: nil)
    let adjustSize = CGSizeMake(size.width, size.height)
    return adjustSize
}

and use it like this :

并像这样使用它:

let

showLabel.frame = CGRectMake(x, y, width , self.ChangeSizeOfLabel("Hello , Height is changing dynamically.....").height)