Width of UILabel created programmatically - ios

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

Related

Create UILabel programmatically and set its position

I want to create a UILabel programmatically from a button click and set its position to the x,y coordinates: (50,50).
The text size can vary between 300 characters to 2,000 characters so I'm using:
[myLabel sizeToFit]
to set the width and height of the label.
This is my code so far:
- (IBAction)createLabel:(id)sender { //create label on button click
UILabel *label;
[label sizeToFit]; //set width and height of label based on text size
//position label
CGRect frame = label.frame;
frame.origin = CGPointMake(50, 50);
label.frame = frame;
label.numberOfLines = 0;
label.lineBreakMode = NSLineBreakByCharWrapping;
label.text = #"This is where the text goes";
[self.view addSubview:label]; //add label to view
}
It doesn't give me any errors when I run the program, but when I press the button to create a label, nothing shows up.
You're not actually creating a label.
UILabel *label;
Just declares a variable, you never initialise it or assign a value to it. You either need a reference to an existing label or you need to create one using initWithFrame:
Also, sizeToFit should be done after you've assigned the text.

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

UITextView within UIScrollView - Dynamic Heights?

I have a UIView which contains a UIScroller - which in turn contains a couple of labels, one image and a dynamic text view.
The text view can contain anything from a few characters to 2000 words - how can I automatically apply the relevant heights to the UITextView and the parent scroller?
I have got as far as the following -
//Set Scroller
[self.scrollerArticle setScrollEnabled:YES];
[self.scrollerArticle setContentSize:CGSizeMake(320, 750)];
[self.articleUITextView sizeToFit];
[self.articleUITextView layoutIfNeeded];
But don't know how to apply the sizetofit method to the scroller?
Try like this,
[self.scrollerArticle setContentSize:CGSizeMake(320, CGRectGetMaxY(self.articleUITextView.frame))];
UITextView is a subclass of UIScrollView and you should use content size after you set up a text to get the size:
self.articleUITextView.text = #"YOUR TEXT";
CGRect rec = self.articleUITextView.frame;
rec.size.height = self.articleUITextView.contentSize.height;
textView.frame = rec;
After that you can just chance contentSize of your scroll view.
If you want to use sizeWithFont: it works fine for UILabels but not necessary with UITextView.
You can get the height of the content using the below method.
-(CGFloat)getContentHeight{
NSString *aMessage = #"My Name is ABC"; // Can be anything between 0 to 2000 chars
CGSize maximumSize = CGSizeMake(320, 9999);
// Use the font you are willing to use for TexTView.
UIFont *textFont = [UIFont fontWithName:#"Helvetica-Bold" size:MessageFontSize];
CGSize myStringSize = [aMessage sizeWithFont:textFont
constrainedToSize:maximumSize
lineBreakMode:NSLineBreakByWordWrapping];
return myStringSize.height;
}
And then can set the ContentSize of Scrollview accordingly.

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.

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