How to adjust and make the width of a UILabel to fit the text size?
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];
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.