UILabel根据要显示的文本自动调整大小 [英] UILabel auto resize on basis of text to be shown

查看:86
本文介绍了UILabel根据要显示的文本自动调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



首先,我是不确定这个我应该使用 UILabel (逻辑上是显示静态文本的最佳选择,在我的情况下)或 UITextView



我希望如何使用它?

我想简单地初始化我的标签或文字使用Text查看此事。
相反,我首先定义框架然后限制我在该区域的文本。



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

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

解决方案

sizeToFit 方法效果很好。



我做了以下。

  UILabel * testLabel = [[UILabel alloc] initWithFrame:CGRectMake(6,3,262,20)]; // RectMake(我想要的xPos,yPos,Max Width,只是一个容器值); 

NSString * test = @这是测试这是测试在这是测试inint这是测试在这是测试在uilabel测试...这是在uilabel的测试...这是测试在uilabel ...这是uilabel的测试......这是uilabel的测试......这是uilabel的测试......这是uilabel的测试...这是uilabel的测试...这是uilabel的测试..这是uilabel的测试...这是uilabel的测试......这是uilabel的测试......这是uilabel的测试......这是uilabel的测试......这是uilabel的测试......这个在uilabel进行测试......这是在uilabel进行测试......;

testLabel.text = test;
testLabel.numberOfLines = 0; //将文本换行到新行
[testLabel sizeToFit];

[self.view addSubview:testLabel];


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.

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.

解决方案

The sizeToFit method worked just great.

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];

这篇关于UILabel根据要显示的文本自动调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆