UILabel - 适合文字的自动尺寸标签? [英] UILabel - auto-size label to fit text?

查看:103
本文介绍了UILabel - 适合文字的自动尺寸标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以自动调整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

你可以更简单地使用 sizeToFit 可从 UIView 类获取的方法,但将行数设置为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 - 适合文字的自动尺寸标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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