[ios] UILabel - auto-size label to fit text?

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?

This question is related to ios iphone objective-c uilabel

The answer is


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

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.


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.

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.


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

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


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


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.


There's also this approach:

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

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


  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

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


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

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to iphone

Detect if the device is iPhone X Xcode 8 shows error that provisioning profile doesn't include signing certificate Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone Certificate has either expired or has been revoked Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve? cordova run with ios error .. Error code 65 for command: xcodebuild with args: "Could not find Developer Disk Image" Reason: no suitable image found iPad Multitasking support requires these orientations How to insert new cell into UITableView in Swift

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to uilabel

How to make a UILabel clickable? Figure out size of UILabel based on String in Swift How to underline a UILabel in swift? Adding space/padding to a UILabel How to set textColor of UILabel in Swift Adjust UILabel height to text Setting UILabel text to bold How do I make an attributed string using Swift? How do I change the font size of a UILabel in Swift? how do I change text in a label with swift?