ios UILabel - 自动调整标签大小以适合文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8796862/
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
UILabel - auto-size label to fit text?
提问by wayneh
Is it possible to auto-resize the UILabel box/bounds to fit the contained text? (I don't care if it ends up larger than the display)
是否可以自动调整 UILabel 框/边界的大小以适合包含的文本?(我不在乎它是否比显示器大)
So if a user enters "hello" or "my name is really long i want it to fit in this box", it is never truncated and the label is 'widened' accordingly?
因此,如果用户输入“你好”或“我的名字真的很长,我希望它适合这个框”,它永远不会被截断并且标签会相应地“加宽”?
采纳答案by Daniel
Please check out my gist where I have made a category for UILabel
for something very similar, my category lets a UILabel
stretch it's height to show all the content: https://gist.github.com/1005520
请查看我的要点,其中我UILabel
为非常相似的内容创建了一个类别,我的类别允许UILabel
拉伸它的高度以显示所有内容:https: //gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
或者看看这篇文章:https: //stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
这会拉伸高度,但你可以轻松地改变它以另一种方式工作并用这样的东西拉伸宽度,这是我相信你想要做的:
@implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
@end
You could more simply use the sizeToFit
method available from the UIView
class, but set the number of lines to 1 to be safe.
您可以更简单地使用类中sizeToFit
可用的方法UIView
,但将行数设置为 1 以确保安全。
iOS 6 update
iOS 6 更新
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
如果您使用的是 AutoLayout,那么您就有了一个内置的解决方案。通过将行数设置为 0,框架将适当调整您的标签大小(增加更多高度)以适合您的文本。
iOS 8 update
iOS 8 更新
sizeWithFont:
is deprecated so use sizeWithAttributes:
instead:
sizeWithFont:
已弃用,因此请sizeWithAttributes:
改用:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
回答by Guilherme Torres Castro
Using [label sizeToFit];
will achieve the same result from Daniels Category.
使用[label sizeToFit];
将获得与 Daniels 类别相同的结果。
Although I recommend to use autolayout and let the label resize itself based on constraints.
虽然我建议使用自动布局并让标签根据约束自行调整大小。
回答by Yogesh Suthar
If we want that UILabel
should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
如果我们希望UILabel
根据文本大小缩小和扩展,那么带有自动布局的故事板是最佳选择。以下是实现这一目标的步骤
Steps
脚步
Put UILabel in view controller and place it wherever you want. Also put
0
fornumberOfLines
property ofUILabel
.Give it Top, Leading and Trailing space pin constraint.
将 UILabel 放在视图控制器中并将其放置在您想要的任何位置。还提出
0
了numberOfLines
财产UILabel
。给它顶部、前导和尾随空间销约束。
- Now it will give warning, Click on the yellow arrow.
- 现在它会发出警告,点击黄色箭头。
- Click on
Update Frame
and click onFix Misplacement
. Now this UILabel will shrink if text is less and expand if text is more.
- 单击
Update Frame
并单击Fix Misplacement
。现在这个 UILabel 将在文本较少时缩小,如果文本较多则扩大。
回答by Suragch
This is not as complicated as some of the other answers make it.
这并不像其他一些答案那样复杂。
Pin the left and top edges
固定左边缘和上边缘
Just use auto layout to add constraints to pin the left and top sides of the label.
只需使用自动布局添加约束来固定标签的左侧和顶部。
After that it will automatically resize.
之后它会自动调整大小。
Notes
笔记
- Don't add constraints for the width and height. Labels have an intrinsicsize based on their text content.
- Thanks to this answerfor help with this.
No need to set
sizeToFit
when using auto layout. My complete code for the example project is here:import UIKit class ViewController: UIViewController { @IBOutlet weak var myLabel: UILabel! @IBAction func changeTextButtonTapped(sender: UIButton) { myLabel.text = "my name is really long i want it to fit in this box" } }
- If you want your label to line wrap then set the number of lines to 0 in IB and add
myLabel.preferredMaxLayoutWidth = 150 // or whatever
in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)
- 不要为宽度和高度添加约束。标签具有基于其文本内容的固有大小。
- 感谢这个答案对此的帮助。
sizeToFit
使用自动布局时无需设置。我的示例项目的完整代码在这里:import UIKit class ViewController: UIViewController { @IBOutlet weak var myLabel: UILabel! @IBAction func changeTextButtonTapped(sender: UIButton) { myLabel.text = "my name is really long i want it to fit in this box" } }
- 如果您希望标签换行,则在 IB 中将行数设置为 0 并添加
myLabel.preferredMaxLayoutWidth = 150 // or whatever
代码。(我还将按钮固定在标签底部,以便在标签高度增加时它会向下移动。)
- If you are looking for dynamically sizing labels inside a
UITableViewCell
then see this answer.
- 如果您正在寻找内部动态调整大小的标签,
UITableViewCell
请参阅此答案。
回答by Gaurav Gilani
Use [label sizeToFit];
to adjust the text in UILabel
使用[label sizeToFit];
调整中的UILabel文本
回答by Doug Baker
I created some methods based Daniel's reply above.
我根据上面 Daniel 的回复创建了一些方法。
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
CGSize maximumLabelSize = CGSizeMake(290, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
return expectedLabelSize.height;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label
{
CGRect newFrame = label.frame;
newFrame.size.height = [self heightForLabel:label withText:label.text];
label.frame = newFrame;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
label.text = text;
[self resizeHeightToFitForLabel:label];
}
回答by Chris Prince
Here's what I am finding works for my situation:
这是我发现适合我的情况的内容:
1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed. 2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is). 3) Then, do:
1) UILabel 的高度有一个 >= 0 使用自动布局的约束。宽度是固定的。2)将文本分配到 UILabel 中,此时它已经有一个超级视图(不确定这有多重要)。3)然后,执行:
label.sizeToFit()
label.layoutIfNeeded()
The height of the label is now set appropriately.
标签的高度现在已适当设置。
回答by Kaijay Lu
@implementation UILabel (UILabel_Auto)
- (void)adjustHeight {
if (self.text == nil) {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
return;
}
CGSize aSize = self.bounds.size;
CGSize tmpSize = CGRectInfinite.size;
tmpSize.width = aSize.width;
tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}
@end
This is category method. You must set text first, than call this method to adjust UILabel's height.
这是类别方法。您必须先设置文本,然后再调用此方法来调整 UILabel 的高度。
回答by vijeesh
You can size your label according to text and other related controls using two ways-
您可以使用两种方式根据文本和其他相关控件调整标签大小 -
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : labelFont } context:nil].size;
适用于 iOS 7.0 及以上
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{ NSFontAttributeName : labelFont } context:nil].size;
before iOS 7.0 this could be used to calculate label size
在 iOS 7.0 之前,这可用于计算标签大小
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
// 根据 labelTextHeight 重构其他控件
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label [label setText:@"label text to set"]; [label sizeToFit];// call this to fit size of the label according to text
如果您不想计算标签文本的大小,则可以在 UILabel 实例上使用 -sizeToFit 作为-
[label setNumberOfLines:0]; // for multiline label [label setText:@"label text to set"]; [label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
// 在此之后,您可以获取标签框架以重新构建其他相关控件
回答by user2941395
- Add missing constraints in storyboard.
- Select UILabel in storyboard and set the attributes "Line" to 0.
- Ref Outlet the UILabel to Controller.h with id:label
- Controller.m and add
[label sizeToFit];
in viewDidLoad
- 在故事板中添加缺少的约束。
- 在 storyboard 中选择 UILabel 并将属性“Line”设置为 0。
- 使用 id:label 将 UILabel 引用到 Controller.h
- Controller.m 并
[label sizeToFit];
在 viewDidLoad 中添加