Get the numberOfLines from a UILabel after resizing it - ios

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.

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's text truncation

I have a UITableView. In that, each cell contains a UILabel. But, text in UILabel is not truncating if it exceeds UIlabel's frames width.
I have tried following options, but nothing is working.
1> set the LineBreakMode as NSLineBreakByTruncatingTail and setNumberOfLines:1
2> set the LineBreakMode as NSLineBreakByWordWrapping and `setNumberOfLines:1
In storyboard also, same settings are present.
Here is the code snippet:
NSString * fullName;
// FullName assignment code
UILabel *label = (UILabel *)[cell.contentView viewWithTag:100];
NSLog(#"textlabel width: %f , text size : %d ", label.bounds.size.width,fullName.length);
label.adjustsFontSizeToFitWidth = NO;
label.text = fullName;
[label setLineBreakMode:NSLineBreakByTruncatingTail];
[label setNumberOfLines:1];
[label sizeToFit];
[label setTextColor:[UIColor whiteColor]];
It's because you do sizeToFit which adjusts the UILabelss width accordingly to its content.
And by the way: Do you have a reason for using tags and not IBOutlet? I think you've set up the UILabelin Storyboard?
Try setting this,
[label setAutoresizingMask:UIViewAutoresizingNone];

UILabel Size to fit is not working

This is what I'm doing. I'm not dynamically creating the label, just picking from the object library.it is working only if I statically increase the height of the label, but I doesn't know at runtime
[self.lblDescription setText:#"This is going to be a test description but a very big description that should increase in height"];
[self.lblDescription sizeToFit];
The label is not going on the next line. But instead it is clipping it as soon as the left of the label reaches the right of the screen
Based on the answers and I tried the following but didn't work:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.lblDescription setText:#"This is going to be a test description but a very big description that should increase in size"];
self.lblDescription.numberOfLines = 0;
[self.lblDescription sizeToFit];
}
I also tried setting -
[self.lblDescription setLineBreakMode:NSLineBreakByWordWrapping];
before calling [self.lblDescription sizeToFit]; but didn't work
Setting adjustsFontSizeToFitWidth property to true did it for me.
Try,
self.lblDescription.adjustsFontSizeToFitWidth = true
(by default it is set to false)
Check for the numberOfLines property
self.lblDescription.numberOfLines = 0;
EDIT : Need to change the height as well (By the comment says) .
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Helvetica Neue" size:19], NSFontAttributeName,
nil];
CGRect expectedLabelFrame = [text boundingRectWithSize:CGSizeMake(571, 500)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
// Adjust the yourLabel the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelFrame.size.height;
yourLabel.frame = newFrame;
I've found that when using sizeToFit with a UILabel, in InterfaceBuilder you need to change the Autoshrink property from 'Fixed Font Size' to 'Minimum Font Size'. I usually then set its value to 0.5 to be sure its working properly.

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 add Multiple Lines in Same UILabel

Any way to have multiple lines of text in UILabel ?
I dont wish to more than 1 label in the view.
How to add multiple lines in a single UILabel??
Yes there is a way. Just you need to add two property of UILabel i.e.
NumberOfLines=0 It'll allow you to add multiple lines in a UILabel
LineBreakMode = NSLineBreakByWordWrapping It'll allow you to break your sentence by word. You can also change it according to your requirement.
[YourLabel setNumberOfLines:0];
[YourLabel setLineBreakMode:NSLineBreakByWordWrapping];
You can also set this two property form your interface builder
here is a sample code
UILabel *pHolder1 = [[UILabel alloc]initWithFrame:CGRectMake(5, 0, 245, 45)];
pHolder1.backgroundColor = [UIColor clearColor];
pHolder1.font = [UIFont systemFontOfSize:14.0f];
pHolder1.numberOfLines =0;
pHolder1.lineBreakMode = NSLineBreakByWordWrapping;
pHolder1.textAlignment = NSTextAlignmentCenter;
Dynamically calculate the height of UILabel
please refer the below post
Adjust UILabel height depending on the text
Here is sample code:
UILabel *lblUsername=[[UILabel alloc] init];
StoryTextSize = [storytext sizeWithFont:[UIFont fontWithName:#"Georgia" size:13.0f] constrainedToSize:CGSizeMake(300, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
lblUsername.frame=CGRectMake(20, 5, [[UIScreen mainScreen] bounds].size.width-40, StoryTextSize.height);
lblUsername.textColor=[UIColor blackColor];
lblUsername.text=[NSString stringWithFormat:#"%#",[[tblRecords objectAtIndex:indexPath.row] valueForKey:#"username"]];
lblStoryText.numberOfLines=nooflines;
lblStoryText.backgroundColor=[UIColor clearColor];
[self.view addSubview:lblStoryText];
make sure that your label height should be more so total no of lines become visible.

Resources