问题描述
是否可以自动调整 UILabel 框/边界的大小以适合所包含的文本?(我不在乎它是否比显示器大)
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)
所以如果用户输入你好"或我的名字真的很长,我希望它适合这个框",它永远不会被截断,标签会相应地加宽"?
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?
推荐答案
请查看我的要点,其中我为 UILabel
创建了一个类别以获取非常相似的内容,我的类别允许 UILabel
拉伸它的高度以显示所有内容:https://gist.github.com/1005520
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
或查看此帖子: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
您可以更简单地使用 UIView
类中提供的 sizeToFit
方法,但将行数设置为 1 以确保安全.
You could more simply use the sizeToFit
method available from the UIView
class, but set the number of lines to 1 to be safe.
如果您使用 AutoLayout,那么您就有了一个内置的解决方案.通过将行数设置为 0,框架将适当调整您的标签大小(增加更多高度)以适合您的文本.
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.
sizeWithFont:
已弃用,因此使用 sizeWithAttributes:
代替:
sizeWithFont:
is deprecated so use sizeWithAttributes:
instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
这篇关于UILabel - 自动调整标签大小以适合文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!