Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to adjust and make the width of a UILabel to fit the text size?

Tags:

iphone

People also ask

How do you change the width of a UILabel?

To change the font or the size of a UILabel in a Storyboard or . XIB file, open it in the interface builder. Select the label and then open up the Attribute Inspector (CMD + Option + 5). Select the button on the font box and then you can change your text size or font.

How do I change the size of labels in Xcode?

You can set the Minimum Font Scale or size in Storyboard/Xib when you set it up in IB under the Attributes inspector. I prefer scale, as it is better at fitting longer text on iPhone 4/5/iPod touches. If you set the size, you can get cut off earlier than with scale.


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.


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

NSString *txt1=@"I am here.";
CGSize stringsize1 = [txt1 sizeWithFont:[UIFont systemFontOfSize:14]]; 
[label setFrame:CGRectMake(x,y,stringsize1.width,hieght)];
[label setText:txt1];

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