UILabel adjust its frame to text length - ios

Is it possible that my UILabel adjusts its frame size to the length of the text of the UILabel?? If yes, how?
Thanks.

Use -sizeToFit:
[label sizeToFit];
And what's more, you can also adjust the font size to fit width:
[label setAdjustsFontSizeToFitWidth:YES];
[label setMinimumFontSize:8.f];

Related

label disappear when use size to fit?

I am displaying a label on UI in iOS using code, not from storyboard. When the size of the label is large then it does display accurate it go outside the view so I decided to use sizeToFit in iOS. But when I apply this thing on label then it does appear on view. Please tell why my label does not appear in this case.
Here is the code for the label:
self.label_company = [[UILabel alloc]initWithFrame:CGRectMake(60, 30, 150, 100)];
[self.label_company setFont:[UIFont fontWithName:#"HelveticaNeue" size:12]];
UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(60, 30, 150, 100)];
[label1 setFont:[UIFont fontWithName:#"HelveticaNeue" size:12]];
label1.text=#"yourdata";
[self.view addSubview:label1];
[label1 sizeToFit];
Make sure you have some text in your label as well as add it to your view.
You currently have no text set to the label hence calling sizeToFit is making its width 0 as there is no size of the label in terms of width.
Set self.label_company.text = #"Some text" and then call sizeToFit
Ensure that you set the text of the label before calling size to fit.

UILabel don't adjust in height to fit the text

I know there is a lot of post about UILabel and it's size but i was unable to find a answer for my problem.
I have some UILabels with a text on 1 line, no more and don't want more lines, and the text is set to a minimum font scale to adjust. In portrait mode, the screen has enough space in heightand don't scale my UILabel in height to a critical point.
In landscape mode, i'm short in height and the UILabel is very small in height and the text is cut on the top and bottom.
I have tested everyting i have read like:
set line breaks to clip mode
use adjustsFontSizeToFitWidth = YES;
In every case, the text fit only in width but don't care about height.
Should i use some ugly hack to calcul the font size depending on the label height myself or have i miss something ?
CGRect labelFrame = CGRectMake(22, 50, 280, 150);
UILabel *myLabel = [[UILabel alloc] initWithFrame:labelFrame];
[myLabel setText:finalRecipe];
[myLabel setBackgroundColor: [UIColor lightGrayColor]];
[myLabel setNumberOfLines:0];
CGFloat fontSize = 0.0f;
labelFrame.size = [myLabel.text sizeWithFont:myLabel.font
minFontSize:myLabel.minimumFontSize
actualFontSize:&fontSize
forWidth:labelFrame.width
lineBreakMode:myLabel.lineBreakMode];
myLabel.frame = labelFrame;
[self.view addSubview:myLabel];

Width of UILabel created programmatically

I'm trying to create a UILabel programmatically that fits it's content.
The best I could do was to use the NSString's method sizeWithAtributes to get it's content's required width and then apply a constraint that fixes the width to that value.
Is this the way it is supposed to be done using autolayout?
if you need some with aoutolayouts, i try comment:
UILabel *testLabel = [UILabel new];
[testLabel setFont:[UIFont systemFontOfSize:16]];
[testLabel setText:#"Test text for size context"];
[testLabel setTextAlignment:NSTextAlignmentLeft];
[testLabel setNumberOfLines:0]; //0 - infiniy lines if not enough space more
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisHorizontal]; // Autolayout rule: The higher the priority, the more important hold the text.. by horizontal
[testLabel setContentHuggingPriority:UILayoutPriorityRequired forAxis:UILayoutConstraintAxisVertical];//some like above but verticale
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisHorizontal];// reverse like Hugging but Compression. then lower priority then text croping.
[testLabel setContentCompressionResistancePriority:UILayoutPriorityDefaultLow forAxis:UILayoutConstraintAxisVertical];
[testLabel preferredMaxLayoutWidth:200];//Start new line each 200 points width
[testLabel setPreferredMaxLayoutWidth:YES];// resize Font size by label size.
[testLabel setTranslatesAutoresizingMaskIntoConstraints:NO]; // Disable autolaresize, enable autolayouts
At First read the best answer for any question about UILabel
And also by using following code you can create dynamic size of UILabel
UILabel *myLabelName = [[UILabel alloc] init];
myLabelName.backgroundColor = [UIColor redColor];
[myLabelName setFont: [UIFont fontWithName:#"OpenSans" size:13]]; // set font and it's size as per your requirement.
myLabelName.textAlignment = NSTextAlignmentLeft;
myLabelName.frame = CGRectMake(lblComplainTitle.frame.origin.x + lblComplainTitle.frame.size.width + 7, lblComplainTitle.frame.origin.y +2, 160, 20);
myLabelName.text = #"This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text, This is my testing text.";
myLabelName.textColor = [UIColor blackColor];
[self setDynamicHeightOfLabel:myLabelName withLblWidth:160 andFontSize:13]; // here in this function you need to pass object of label with width (as you wabt) and font size
[self.view addSubview:myLabelName];
Code of function, name is setDynamicHeightOfLabel:withLblWidth:andFontSize
-(void) setDynamicHeightOfLabel:(UILabel *) myLabel withLblWidth:(CGFloat) width andFontSize:(int) fontSize
{
CGSize myLabelSize = CGSizeMake(width, FLT_MAX);
CGSize expecteingmyLabelSize = [myLabel.text sizeWithFont:myLabel.font constrainedToSize:myLabelSize lineBreakMode:myLabel.lineBreakMode];
CGRect lblFrame = myLabel.frame;
lblFrame.size.height = expecteingmyLabelSize.height;
myLabel.frame = lblFrame;
int addressLine = myLabel.frame.size.height/fontSize;
myLabel.numberOfLines = addressLine;
}
I create function because you can create any label with dynamic size without use of repeated code.
There is a couple of steps that you have to do to achieve this using autolayout.
Set layout constrains for the label.
Set height constraint with low priority.
Set numberOfLines to 0 to allow multiline text.
Set preferredMaxLayoutWidth for the label.
The preferredMaxLayoutWidth is used by label to calculate its height.
This property affects the size of the label when layout constraints
are applied to it. During layout, if the text extends beyond the width
specified by this property, the additional text is flowed to one or
more new lines, thereby increasing the height of the label.
Hi you can manage the width of lable by doing so programatically,
CGRect frame;
frame =self.yourLabel.frame;
frame.size.width +=20;
self.yourLabel.frame=frame;
Thanks

How does a UILabel's minimumScaleFactor work?

I have used minimumFontSize before but that function is now deprecated and i don't quite understand how minimumScaleFactor works.
I want the maximum font size to be 10 and the minimum to be 7.
How can I achieve the re-size down to font size 7 with the scale factor?
UILabel creation:
UILabel *label = [[UILabel alloc] init];
[label setTranslatesAutoresizingMaskIntoConstraints:NO];
label.text = [labelName uppercaseString];
label.textAlignment = NSTextAlignmentCenter;
label.textColor = [UIColor whiteColor];
label.font = [UIFont fontWithName:HELVETICA_FONT_STYLE_BOLD size:9.5];
label.backgroundColor = [UIColor clearColor];
label.minimumScaleFactor = .1f;
[label addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:#"H:[label(WIDTH)]"
options:0
metrics:#{#"WIDTH" : [NSNumber numberWithFloat:buttonSize.width]}
views:NSDictionaryOfVariableBindings(label)]];
[contentView addSubview:label];
You need to set the label.adjustsFontSizeToFitWidth = YES;
In addition to what the other answers say, if you put minSize/defaultSize (division) as the minimumScaleFactor, it will be the same as using the old minimumFontSize.
Ex, if you want the minimum font size to be 10 using default label size, you can do:
[label setMinimumScaleFactor:10.0/[UIFont labelFontSize]];
(Replace [UIFont labelFontSize] with your label's font size if it is not the default).
which would be the same as:
[label setMinimumFontSize:10.0];
According to the documentation:
Use this property to specify the smallest multiplier for the current font size that yields an acceptable font size to use when displaying the label’s text. If you specify a value of 0 for this property, the current font size is used as the smallest font size.
So if default font size for your label is 10, you put 0.7f as a minimumScaleFactorand it should do the same thing as minimumFontSize did.
In addition to other answers, I'm going to add a beginner-friendly explanation that helped myself:
How to calculate a minimumScaleFactor? Divide your label's minimum font size by your label's default font size. For example, your default font size is 25. Your minimum font size is 10.
10/25 = 0.4
0.4 is your minimumScaleFactor value. Also see #Jsdodgers's answer above.

Get the numberOfLines from a UILabel after resizing it

I do this to make my UIlabel, setting the numberOfLines to 0 so that it has no line-limit:
UILabel *nmLbl = [[UILabel alloc] initWithFrame:CGRectZero];
[nmLbl setFont:[UIFont boldSystemFontOfSize:16.0f]];
[nmLbl setNumberOfLines:0];
[self addSubview:nmLbl];
[nmLbl release];
Later on, when I know which string goes into the label, I size it like this:
nameSize = [[self name] sizeWithFont:[UIFont boldSystemFontOfSize:16.0f] constrainedToSize:maxNameSize lineBreakMode:UILineBreakModeWordWrap];
[self.nameLabel setFrame:CGRectMake(0.0f, 0.0f, nameSize.width, nameSize.height)];
[self.nameLabel sizeToFit];
Now, for my particular use, I need to know how many lines this ends up taking.
If I access the numberOfLines property of the UILabel it will always return 0.
Is there a way for me to directly access how many lines the UILabel ended up being without
having to calculate it, again, by going label.size.height / fontHeight?
Thank you in advance.
No. numberOfLines is a configuration setting, not a reflection of the current formatting.

Resources