UILabel - 自动调整标签大小以适合文本?

发布于 2024-12-26 05:40:38 字数 126 浏览 3 评论 0原文

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

陌路黄昏 2025-01-02 05:40:38

请查看我的要点,其中我为 UILabel 创建了一个非常相似的类别,我的类别让 UILabel 拉伸其高度以显示所有内容:https://gist.github.com/1005520

或者查看这篇文章:https://stackoverflow.com/a/7242981/662605

这会拉伸高度,但您可以轻松更改它以进行工作另一种方式并用这样的方法拉伸宽度,我相信这就是您想要做的:

@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 类,但为了安全起见,将行数设置为 1。


iOS 6 更新

如果您使用 AutoLayout,那么您就有一个内置的解决方案。通过将行数设置为 0,框架将适当调整标签大小(添加更多高度)以适合您的文本。


iOS 8 更新

sizeWithFont: 已弃用,因此请使用 sizeWithAttributes: 代替:

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];

    return expectedLabelSize.width;
}

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

Or check out this post: 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.


iOS 6 update

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.


iOS 8 update

sizeWithFont: is deprecated so use sizeWithAttributes: instead:

- (float)expectedWidth{
    [self setNumberOfLines:1];

    CGSize expectedLabelSize = [[self text] sizeWithAttributes:@{NSFontAttributeName:self.font}];

    return expectedLabelSize.width;
}
如梦亦如幻 2025-01-02 05:40:38

使用 [label sizeToFit]; 将从 Daniels 类别中获得相同的结果。

尽管我建议使用自动布局并让标签根据约束自行调整大小。

Using [label sizeToFit]; will achieve the same result from Daniels Category.

Although I recommend to use autolayout and let the label resize itself based on constraints.

烂柯人 2025-01-02 05:40:38

如果我们希望 UILabel 根据文本大小缩小和扩展,那么带有自动布局的故事板是最好的选择。以下是实现此目的的步骤 步骤

  1. 将 UILabel 放入视图控制器中并将其放置在您想要的任何位置。还要为 UILabelnumberOfLines 属性设置 0

  2. 给予顶部、前导和尾随空格引脚约束。

在此处输入图像描述

  1. 现在会发出警告,单击黄色箭头。

在此处输入图像描述

  1. 单击更新框架,然后单击修复错位。现在,如果文本较少,此 UILabel 将缩小;如果文本较多,则此 UILabel 将扩展。

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

Steps

  1. Put UILabel in view controller and place it wherever you want. Also put 0 for numberOfLines property of UILabel.

  2. Give it Top, Leading and Trailing space pin constraint.

enter image description here

  1. Now it will give warning, Click on the yellow arrow.

enter image description here

  1. Click on Update Frame and click on Fix Misplacement. Now this UILabel will shrink if text is less and expand if text is more.
一抹苦笑 2025-01-02 05:40:38

这并不像其他一些答案那么复杂。

输入图像描述这里

固定左侧和顶部边缘

只需使用自动布局添加约束即可固定标签的左侧和顶部边缘。

输入图像描述这里

之后它会自动调整大小。

注意

  • 不要添加宽度和高度的约束。标签具有基于其文本内容的固有尺寸。
  • 感谢此答案提供帮助。
  • 使用自动布局时无需设置sizeToFit。我的示例项目的完整代码在这里:

    导入 UIKit
    类 ViewController: UIViewController {
    
        @IBOutlet 弱变量 myLabel:UILabel!
    
        @IBAction func changeTextButtonTapped(发送者:UIButton){
            myLabel.text =“我的名字很长,我希望它适合这个盒子”
        }
    }
    
  • 如果您希望标签自动换行,请在 IB 中将行数设置为 0,并在代码中添加 myLabel.preferredMaxLayoutWidth = 150 // 或其他内容。 (我还将按钮固定在标签底部,以便当标签高度增加时它会向下移动。)

在此处输入图像描述

  • 如果您正在寻找 UITableViewCell 内动态调整大小的标签然后看这个答案

输入图像描述这里

This is not as complicated as some of the other answers make it.

enter image description here

Pin the left and top edges

Just use auto layout to add constraints to pin the left and top sides of the label.

enter image description here

After that it will automatically resize.

Notes

  • Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
  • Thanks to this answer for 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.)

enter image description here

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.

enter image description here

请你别敷衍 2025-01-02 05:40:38

使用[label sizeToFit];调整UILabel中的文本

Use [label sizeToFit]; to adjust the text in UILabel

偏闹i 2025-01-02 05:40:38

这是我发现适合我的情况的方法:

1)使用自动布局时,UILabel 的高度有 >= 0 约束。宽度是固定的。
2)将文本分配到 UILabel 中,此时它已经有一个超级视图(不确定这有多重要)。
3) 然后,执行以下操作:

    label.sizeToFit()
    label.layoutIfNeeded()

现在标签的高度已设置适当。

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:

    label.sizeToFit()
    label.layoutIfNeeded()

The height of the label is now set appropriately.

云雾 2025-01-02 05:40:38

我根据上面丹尼尔的回复创建了一些方法。

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

I created some methods based Daniel's reply above.

-(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];
}
凹づ凸ル 2025-01-02 05:40:38
@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

这就是分类法。您必须先设置文本,然后调用此方法来调整 UILabel 的高度。

@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.

淑女气质 2025-01-02 05:40:38

您可以使用两种方式根据文本和其他相关控件调整标签大小

  1. -

    适用于 iOS 7.0 及更高版本

    CGSize labelTextSize = [labelTextboundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
                                              选项:NSStringDrawingUsesLineFragmentOrigin
                                           属性:@{
                                                        NSFontAttributeName : labelFont
                                                        }
                                              上下文:nil].size;
    

iOS 7.0 之前的更高版本,这可用于计算标签大小

CGSize labelTextSize = [label.text sizeWithFont:label.font 
                            constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)  
                                lineBreakMode:NSLineBreakByWordWrapping];

// 基于 labelTextHeight 重新构建其他控件

CGFloat labelTextHeight = labelTextSize.height;
  1. 如果您不想计算标签文本的大小可以在 UILabel 实例上使用 -sizeToFit 作为-

    [标签 setNumberOfLines:0]; // 对于多行标签
    [label setText:@"要设置的标签文本"];
    [label sizeToFit];//调用此函数以根据文本调整标签的大小
    

// 之后您可以获得标签框架来重新构建其他相关控件

You can size your label according to text and other related controls using two ways-

  1. For iOS 7.0 and above

    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

CGSize labelTextSize = [label.text sizeWithFont:label.font 
                            constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)  
                                lineBreakMode:NSLineBreakByWordWrapping];

// reframe other controls based on labelTextHeight

CGFloat labelTextHeight = labelTextSize.height;
  1. 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
    

// after this you can get the label frame to reframe other related controls

只怪假的太真实 2025-01-02 05:40:38

sizeToFit() 方法在约束条件下不能很好地发挥作用,但从 iOS 9 开始,这就是您所需要的 -

label.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width).activate()

the sizeToFit() method doesn't play well with constraints, but as of iOS 9 this is all you need -

label.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width).activate()
国际总奸 2025-01-02 05:40:38
  1. 在故事板中添加缺少的约束。
  2. 在 Storyboard 中选择 UILabel,并将属性“Line”设置为 0。
  3. 将 UILabel 引用到 Controller.h,id:label
  4. Controller.m 并在 viewDidLoad 中添加 [label sizeToFit];
  1. Add missing constraints in storyboard.
  2. Select UILabel in storyboard and set the attributes "Line" to 0.
  3. Ref Outlet the UILabel to Controller.h with id:label
  4. Controller.m and add [label sizeToFit]; in viewDidLoad
隱形的亼 2025-01-02 05:40:38

我在自动布局方面遇到了很大的问题。
表格单元格内有两个容器。第二个容器根据项目描述(0 - 1000 个字符)调整大小,并且应根据它们调整行大小。

缺少的成分是描述的底部约束。

我已将动态元素的底部约束从 = 0 更改为 >= 0

I had a huge problems with auto layout.
We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.

The missing ingredient was bottom constraint for description.

I've changed bottom constraint of dynamic element from = 0 to >= 0.

半城柳色半声笛 2025-01-02 05:40:38

每次都适合! :)

    name.text = @"Hi this the text I want to fit to"
    UIFont * font = 14.0f;
    CGSize size = [name.text sizeWithAttributes:@{NSFontAttributeName: font}];
    nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
    nameOfAssessment.font = [UIFont systemFontOfSize:font];

Fits everytime! :)

    name.text = @"Hi this the text I want to fit to"
    UIFont * font = 14.0f;
    CGSize size = [name.text sizeWithAttributes:@{NSFontAttributeName: font}];
    nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
    nameOfAssessment.font = [UIFont systemFontOfSize:font];
伴随着你 2025-01-02 05:40:38

您可以显示一行输出,然后设置属性 Line=0 并显示多行输出,然后设置属性 Line=1 及更多

[self.yourLableName sizeToFit];

you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more

[self.yourLableName sizeToFit];
圈圈圆圆圈圈 2025-01-02 05:40:38

还有这样的做法:

[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];

There's also this approach:

[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文