UILabel—自动大小标签以适合文本?

时间:2021-08-16 21:40:14

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?

因此,如果用户输入“hello”或“my name is really long i want it to fit in this box”,它就不会被截断,标签也不会相应被“加宽”?

14 个解决方案

#1


93  

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://*.com/a/7242981/662605

或者看看这篇文章:https://*.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.

您可以更简单地使用来自UIView类的sizeToFit方法,但是将行数设置为1以确保安全。


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.

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

#2


63  

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

使用[标签sizeToFit];将获得相同的结果从丹尼尔斯类别。

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

尽管我建议使用autolayout并让标签根据约束调整自身大小。

#3


27  

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根据文本大小进行收缩和扩展,那么使用autolayout的故事板是最好的选择。下面是实现这一目标的步骤

Steps

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

    将UILabel放在视图控制器中,并将其放置到任何您想要的位置。也为UILabel的numberOfLines属性设0。

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

    给它顶部,前导和后导的空间引脚约束。

UILabel—自动大小标签以适合文本?

  1. Now it will give warning, Click on the yellow arrow.
  2. 现在它会发出警告,点击黄色箭头。

UILabel—自动大小标签以适合文本?

  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.
  2. 单击更新框架并单击Fix错位。现在这个UILabel会在文本少的时候缩小,在文本多的时候扩展。

#4


18  

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

这并不像其他一些答案所描述的那么复杂。

UILabel—自动大小标签以适合文本?

Pin the left and top edges

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

只需使用自动布局来添加约束来固定标签的左边和上边。

UILabel—自动大小标签以适合文本?

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:

    使用自动布局时不需要设置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"
        }
    }
    
  • 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.)
  • 如果您想让标签行换行,那么在IB中将行数设置为0,并添加myLabel。preferredMaxLayoutWidth = 150 //或任何代码。(我还将按钮固定在标签的底部,以便当标签高度增加时,它会向下移动。)

UILabel—自动大小标签以适合文本?

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.
  • 如果您正在UITableViewCell中寻找动态大小标签,那么请查看这个答案。

UILabel—自动大小标签以适合文本?

#5


9  

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

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

#6


5  

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

#7


3  

@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的高度。

#8


2  

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

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

  1. For iOS 7.0 and above

    适用于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

// reframe基于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-

    如果您不想计算标签文本的大小,那么可以在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

//在此之后,您可以让标签框架重新框架其他相关控件

#9


2  

  1. Add missing constraints in storyboard.
  2. 在故事板中添加缺失的约束。
  3. Select UILabel in storyboard and set the attributes "Line" to 0.
  4. 在故事板中选择UILabel并将属性“Line”设置为0。
  5. Ref Outlet the UILabel to Controller.h with id:label
  6. Ref输出UILabel到控制器。h和id:标签
  7. Controller.m and add [label sizeToFit]; in viewDidLoad
  8. 控制器。m并添加[标签尺寸合适];在viewDidLoad

#10


1  

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.

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

The missing ingredient was bottom constraint for description.

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

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

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

#11


0  

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

#12


0  

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

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

[self.yourLableName sizeToFit];

#13


0  

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)使用autolayout的高度有>= 0约束。宽度是固定的。2)将文本分配到UILabel中,UILabel此时已经有一个超视图(不确定这有多重要)。3)然后,做:

    label.sizeToFit()
    label.layoutIfNeeded()

The height of the label is now set appropriately.

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

#14


-1  

There's also this approach:

这种方法还有:

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

#1


93  

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://*.com/a/7242981/662605

或者看看这篇文章:https://*.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.

您可以更简单地使用来自UIView类的sizeToFit方法,但是将行数设置为1以确保安全。


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.

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

#2


63  

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

使用[标签sizeToFit];将获得相同的结果从丹尼尔斯类别。

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

尽管我建议使用autolayout并让标签根据约束调整自身大小。

#3


27  

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根据文本大小进行收缩和扩展,那么使用autolayout的故事板是最好的选择。下面是实现这一目标的步骤

Steps

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

    将UILabel放在视图控制器中,并将其放置到任何您想要的位置。也为UILabel的numberOfLines属性设0。

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

    给它顶部,前导和后导的空间引脚约束。

UILabel—自动大小标签以适合文本?

  1. Now it will give warning, Click on the yellow arrow.
  2. 现在它会发出警告,点击黄色箭头。

UILabel—自动大小标签以适合文本?

  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.
  2. 单击更新框架并单击Fix错位。现在这个UILabel会在文本少的时候缩小,在文本多的时候扩展。

#4


18  

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

这并不像其他一些答案所描述的那么复杂。

UILabel—自动大小标签以适合文本?

Pin the left and top edges

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

只需使用自动布局来添加约束来固定标签的左边和上边。

UILabel—自动大小标签以适合文本?

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:

    使用自动布局时不需要设置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"
        }
    }
    
  • 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.)
  • 如果您想让标签行换行,那么在IB中将行数设置为0,并添加myLabel。preferredMaxLayoutWidth = 150 //或任何代码。(我还将按钮固定在标签的底部,以便当标签高度增加时,它会向下移动。)

UILabel—自动大小标签以适合文本?

  • If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.
  • 如果您正在UITableViewCell中寻找动态大小标签,那么请查看这个答案。

UILabel—自动大小标签以适合文本?

#5


9  

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

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

#6


5  

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

#7


3  

@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的高度。

#8


2  

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

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

  1. For iOS 7.0 and above

    适用于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

// reframe基于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-

    如果您不想计算标签文本的大小,那么可以在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

//在此之后,您可以让标签框架重新框架其他相关控件

#9


2  

  1. Add missing constraints in storyboard.
  2. 在故事板中添加缺失的约束。
  3. Select UILabel in storyboard and set the attributes "Line" to 0.
  4. 在故事板中选择UILabel并将属性“Line”设置为0。
  5. Ref Outlet the UILabel to Controller.h with id:label
  6. Ref输出UILabel到控制器。h和id:标签
  7. Controller.m and add [label sizeToFit]; in viewDidLoad
  8. 控制器。m并添加[标签尺寸合适];在viewDidLoad

#10


1  

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.

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

The missing ingredient was bottom constraint for description.

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

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

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

#11


0  

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

#12


0  

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

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

[self.yourLableName sizeToFit];

#13


0  

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)使用autolayout的高度有>= 0约束。宽度是固定的。2)将文本分配到UILabel中,UILabel此时已经有一个超视图(不确定这有多重要)。3)然后,做:

    label.sizeToFit()
    label.layoutIfNeeded()

The height of the label is now set appropriately.

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

#14


-1  

There's also this approach:

这种方法还有:

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