56

In my project, there is a UILabel with text. The font size is 16pt. The text contents are changed depending on different cases. I hope it can automatically adjust the width of UILabel to fit the total width of texts without stretching.

Is it possible?

Forge
  • 6,538
  • 6
  • 44
  • 64
arachide
  • 8,006
  • 18
  • 71
  • 134

8 Answers8

115

This assumes you have already set the font:

label.text = @"some text";
[label sizeToFit];

You will also need to define a maximum width, and tell your program what to do if sizeToFit gives you a width greater than that maximum.

William Jockusch
  • 26,513
  • 49
  • 182
  • 323
21

Here's how to do it, suppose the following messageLabel is the label you want to have the desired effect. Now, try these simple line of codes:

    // Set width constraint for label; it's actually the width of your UILabel
    CGFloat constrainedWidth = 240.0f;
    // Calculate space for the specified string
    CGSize sizeOfText = [yourText sizeWithFont:yourFont constrainedToSize:CGSizeMake(constrainedWidth, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap];
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectMake(20,20,constrainedWidth,sizeOfText.height)];
    messageLabel.text = yourText;
    messageLabel.numberOfLines = 0;// This will make the label multiline
Forge
  • 6,538
  • 6
  • 44
  • 64
Munim
  • 2,626
  • 1
  • 19
  • 28
  • 7
    This is actually a really good answer... Just not for this specific question! This answer works well when you want to automatically adjust the *height* of a `UILabel` whilst maintaining a fixed width. That's in fact what I was looking for when I came across this page. I'd love to vote your answer up... but it doesn't answer the question asked. Good solution nevertheless and will probably help others who stumble across this page. – Jonathan Ellis Apr 23 '12 at 15:23
  • 1
    Thanks jon! Actually I was searching for this solution as well and incidentally I managed to make it,and then thought I should share it here. :) BTW,exactly what happened that time is that I didn't notice the question very well, so made the mistake,I think. Sorry for that,and happy that it helped you :D – Munim Apr 23 '12 at 16:53
  • could you post something similar for iOS 8? – user2159978 Nov 18 '14 at 08:59
14
NSString *txt1=@"I am here.";
CGSize stringsize1 = [txt1 sizeWithFont:[UIFont systemFontOfSize:14]]; 
[label setFrame:CGRectMake(x,y,stringsize1.width,hieght)];
[label setText:txt1];
Vikas Pandey
  • 550
  • 4
  • 13
7

I see three options here.

First, make label's size big enough to hold any text. That's most simple, but does not always work well - depends on its surrounding views.

Second, Label can adapt size of the font for longer text (adjustsFontSizeToFitWidth property). This is often not desirable, different fonts in elements might look ugly.

Last option is to programmatically resize the label according to its currently holding text. To calculate the size required to hold the text with current font use something like this:

CGSize textSize = [[someLabel text] sizeWithFont:[someLabel font] forWidth:someLabel.bounds.size.width lineBreakMode:UILineBreakModeWordWrap];
Forge
  • 6,538
  • 6
  • 44
  • 64
Michal
  • 4,846
  • 3
  • 33
  • 25
  • If we use UILineBreakModeWordWrap we can enter multiple lines on UILabel, How can I set the line space between two lines. – Vineesh TP Jul 04 '12 at 09:40
3

If you set your font and its size already and if you have your frame defined, try using the following for these two common conditions:

if (label.text.length > maxCharPerLine) [label setNumberOfLines:0]; // infinite lines
else [label setNumberOfLines:1]; // one line only

// Adjust your font size to fit your desired width.
[label setAdjustsFontSizeToFitWidth:YES];
Will Von Ullrich
  • 2,129
  • 2
  • 15
  • 42
dheeru
  • 319
  • 5
  • 6
  • Assuming you are attempting multiple line labeling then yes this is the correct approach. For single line labeling of course set number of lines to 1. – Will Von Ullrich Mar 07 '17 at 18:19
2

Using Auto Layout:

enter image description here

In the ViewController:

override func viewDidLoad() {
    super.viewDidLoad()

    sampleLabel.text = "Electrical Maintenance and Repair"
    sampleLabel.sizeToFit()
}
mokagio
  • 16,391
  • 3
  • 51
  • 58
Alvin George
  • 14,148
  • 92
  • 64
1

Follow this.

CGSize stringsize = [yourString sizeWithFont:[UIFont systemFontOfSize:fontSize]]; 
[label setFrame:CGRectMake(x,y,stringsize.width,height)];
[label setText: yourString];
Forge
  • 6,538
  • 6
  • 44
  • 64
1

As sizeWithFont is depreciated in IOS 7.0 then you below code

#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)



 if (SYSTEM_VERSION_LESS_THAN(@"7.0")) {
        // code here for iOS 5.0,6.0 and so on
        CGSize fontSize = [itemCat_text sizeWithFont:[UIFont fontWithName:@"Helvetica" size:12]];
    } else {
        // code here for iOS 7.0
         fontSize = [itemCat_text sizeWithAttributes:
                           @{NSFontAttributeName:
                                 [UIFont fontWithName:@"Helvetica" size:12]}];
    }
9to5ios
  • 5,319
  • 2
  • 37
  • 65