14

I have searched the solution to this in the past QAs, but could not find the right one.
Does anyone know how to adjust aUILabel size dynamically to fit the text length?
I have uploaded the screen shot of what I don't want(1st line) and what I want(2nd line).
I'd appreciate any clues, advice or code sample. Thank you.enter image description here

Édouard Lopez
  • 32,718
  • 23
  • 108
  • 161
boochan224
  • 371
  • 1
  • 4
  • 13

8 Answers8

13

What you are searching is the UILabel method sizeToFit

I can try to explain to you, but the best answer to know how to work with UILabel is that: https://stackoverflow.com/a/1054681/666479

Community
  • 1
  • 1
ggrana
  • 2,225
  • 2
  • 19
  • 28
6

Xcode 8 and iOS 10

This is quite easy to do with Auto Layout. No need to do anything in code.

enter image description here

Use Auto Layout

Use auto layout to pin each label's top and left edges only. Don't add constraints for the width and height. The view's intrinsic content size will take care of that.

enter image description here

Here is what the constraints look like:

enter image description here

Code

There is nothing at all special about the code. No need to use sizeToFit or anything like that.

import UIKit
class ViewController: UIViewController {

    @IBOutlet weak var labelOne: UILabel!
    @IBOutlet weak var labelTwo: UILabel!
    @IBOutlet weak var labelThree: UILabel!

    @IBAction func changeTextButtonTapped(_ sender: UIButton) {

        labelOne.text = "David"
        labelTwo.text = "met"
        labelThree.text = "her"
    }
}

Notes

  • This answer has been retested with Xcode 8, iOS 10, and Swift 3.
  • See my other answer if you want multi-line resizing.
  • Thanks to this answer for setting me on the right track.
Community
  • 1
  • 1
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
  • 1
    If you're using auto-layout, this is the right answer. I was initially worried about not fully constraining the layout, but it's documented to work this way so it should be good. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ViewswithIntrinsicContentSize.html – Andy Mortimer May 29 '16 at 06:56
  • gives error for add missing contrinats how to handle that? – KOTIOS Feb 16 '17 at 05:48
  • @MyMasterPeice, I have retested this example in Xcode 8 and I don't get any missing constraints error. I added an image with the exact constrains that I am using. Try copying this exact example. You shouldn't get any errors. – Suragch Feb 20 '17 at 01:05
  • @Suragch i havnt seen ur demo app but i tried that same thing in textview which is placed directly in content view where in this solution didnt worked but if we wrap textview in UIView then it is just perfect answer , that is tricky point which was not mentioned in answer but thats what worked for me ! – KOTIOS Feb 20 '17 at 02:51
  • @MyMasterPeice, Ok, I haven't used content views much, so I assumed it worked the same everywhere. Thanks for your response. I'm glad you got it working. – Suragch Feb 20 '17 at 04:00
  • @Suragch yep but this may be one tricky point else this solution is better +1 :) – KOTIOS Feb 20 '17 at 04:16
3

Use This Extended UILabel class:

//
//  UILabelExtended.h

//
//  Created by Prateek on 6/18/11.



#import <Foundation/Foundation.h>

/*  **********************************************************************************************
        This class inherit the class UILabel and extend the features of UILabel. 
    ********************************************************************************************** */
@interface UILabelExtended : UILabel {
   __unsafe_unretained id  customDelegate;
    id  objectInfo;
    SEL selector;
}

@property (nonatomic,assign) SEL selector;;
@property (nonatomic,assign) id  customDelegate;
@property (nonatomic,retain) id  objectInfo;
@end

@interface UILabel(UILabelCategory)
- (void)setHeightOfLabel;
- (void)setWidthOfLabel;
- (void)setHeightOfLabelWithMaxHeight:(float)maxHeight;
- (void)setWidthOfLabelWithMaxWidth:(float)maxWidth ;
@end

UILabelExtended.m

//
//  Created by Prateek on 6/18/11.

//

#import "UILabelExtended.h"


@implementation UILabelExtended
@synthesize selector,customDelegate, objectInfo;

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    if(self.selector)
        if([self.customDelegate respondsToSelector:self.selector]) {
            [self.customDelegate performSelector:self.selector withObject:self];
            return;
        }
}

- (void)dealloc {

    self.customDelegate = nil;
    self.selector = NULL;
    self.objectInfo = nil;
}
@end


@implementation UILabel(UILabelCategory)

- (void)setHeightOfLabel {
    UILabel* label = self;

    //get the height of label content
    CGFloat height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, 99999) lineBreakMode:NSLineBreakByWordWrapping].height;
    //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        frame.size.height = height;
    } 
    else {
        frame.size.height = 0;
    }
    label.frame = frame;
}


- (void)setWidthOfLabel {
    UILabel* label = self;

        //get the height of label content
    CGFloat width = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(99999, label.bounds.size.height) lineBreakMode:NSLineBreakByWordWrapping].width;
        //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        frame.size.width = width+5;
    } 
    else {
        frame.size.width = 0;
    }
    label.frame = frame;
}

- (void)setHeightOfLabelWithMaxHeight:(float)maxHeight {
    UILabel* label = self;

    //get the height of label content
    CGFloat height = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(label.bounds.size.width, maxHeight) lineBreakMode:NSLineBreakByWordWrapping].height;
    //set the frame according to calculated height
    CGRect frame = label.frame;

    if([label.text length] > 0) {
        if (height > maxHeight) {
            frame.size.height = maxHeight;
        }
        else {
            frame.size.height = height;
        }

    } 
    else {
        frame.size.height = 0;
    }
    label.frame = frame;
}

- (void)setWidthOfLabelWithMaxWidth:(float)maxWidth  {
    UILabel* label = self;

    //get the height of label content
    CGFloat width = [label.text sizeWithFont:label.font constrainedToSize:CGSizeMake(99999, label.bounds.size.height) lineBreakMode:NSLineBreakByWordWrapping].width;
    //set the frame according to calculated height
    CGRect frame = label.frame;
    if([label.text length] > 0) {

        if (width > maxWidth) {
            frame.size.width = maxWidth;
        }
        else {
            frame.size.width = width;
        }
    } 
    else {
        frame.size.width = 0;
    }
    label.frame = frame;
}
@end

Use Methods: 1) set text of UILabel 2) [yourLBLObj setHeightOfLabel]; or [yourLBLObj setWidthOfLabel]; It will automatically set Height or Width according to text.

Prateek Prem
  • 1,544
  • 11
  • 13
3

you get simply calculate UILabel width for string size,try this simple code for set UILabel size

   // Single line, no wrapping;
    CGSize expectedLabelSize = [string sizeWithFont:yourFont];
 //  you get width,height in expectedLabelSize;
//expectedLabelSize.width,expectedLabelSize.height
NANNAV
  • 4,718
  • 4
  • 26
  • 48
1

try this

        NSString *text1 = [NSString stringWithFormat:@"%@",commentText];
        CGSize constraint1 = CGSizeMake(280, 2000);
        CGSize size1 = [text1 sizeWithFont:[UIFont systemFontOfSize:12] constrainedToSize:constraint1 lineBreakMode:UILineBreakModeWordWrap];

        UILabel *lblComment = [[UILabel alloc] initWithFrame:CGRectMake(posx,posy,size1.width,size1.height)] ;
        lblComment.lineBreakMode = UILineBreakModeWordWrap;
        lblComment.numberOfLines = size1.height/15;
        [lblComment setFont:[UIFont systemFontOfSize:12]];
        lblComment.text = text1;
        lblComment.tag = shareObjC.userId;
            [lblComment setNeedsDisplay]
SAMIR RATHOD
  • 3,500
  • 1
  • 16
  • 42
0

You can use this piece of code for calculate label width and set it

   CGSize expectedLabelSize = [name sizeWithFont:yourfont constrainedToSize:maximumLabelSize]; 

// you can get width width height from expectedLabelSize and set accordingly

the1pawan
  • 1,204
  • 9
  • 26
0

Currently i m working on IOS-8 and there is small changes i made to @Suragch answer (Need to use auto layout to make this work)

Below is the step and screenshot in result :

  1. Place the textview inside UIView and not directly inside content-view in storyboard
  2. Disable scroll of textview from storyboard
  3. Add Leading and top constraints as i have added to view in below screenshot(Trailing constraint is optional but i have added )

There is no need to add code in swift this can be done in storyboard itself.

Result : enter image description here

KOTIOS
  • 10,974
  • 3
  • 34
  • 61
0

All you need to just put 2 lines code

lbl1.numberOfLines = 0
    lbl1.sizeToFit()

It will manage label width as per its content

Hope it helps others :)

Anjali jariwala
  • 360
  • 3
  • 13