How can I prevent sizeToFit from changing the UILabel width? - ios

I have a UILabel right now and the UILabel.text value changes regularly.
The problem I am having is that if each time the UILabel.text value changes, the UILabel width changes according to the content of the label.
How can I fix this? This is my code I have right now:
outputLabel.text = errorMessage;
outputLabel.hidden = NO;
[outputLabel sizeToFit];
UPDATE
The reason I am using sizeToFit is because I need the height to automatically change.
Thanks,
Peter

you can create a category or a subclass of UILabel and add this method to resize only the height of the label depending to the input text
- (void)heightToFit {
CGSize maxSize = CGSizeMake(self.frame.size.width, CGFLOAT_MAX);
CGSize textSize = [self.text sizeWithFont:self.font constrainedToSize:maxSize lineBreakMode:self.lineBreakMode];
CGRect labelRect = self.frame;
labelRect.size.height = textSize.height;
[self setFrame:labelRect];
}
and use it instead sizeToFit

Use [UILabel sizeThatFits:] with a CGSize with infinite height like (320, 10000).

I subclassed UILabel and overrode the sizeThatFits method to look like this:
- (CGSize)sizeThatFits:(CGSize)size
{
CGSize res = [super sizeThatFits:size];
return CGSizeMake(size.width, res.height);
}
Then if I add the label into a nib I place a UILabel from the object library. After that I make sure to set the class of the placed label to my custom class instead of the default of UILabel.
It basically just overrides the new width with the original width so it never changes width, but dynamically changes height.

Use following trick to do the job done:
First is set tag of uiLabel. My cell.yourLable tag is 998
cell.yourLable.numberOfLines = 0;
[cell.yourLable sizeToFit];
UILabel *myLbl=[cell.contentView viewWithTag:998];
CGRect frm=cell.yourLable.frame;
frm.size.width = cell.contentView.frame.size.width;
myLbl.frame=frm;
Here the trick is to get same UiLabel by tag and set its width by setting frame.

Related

Create non-constant width for UILabel in Interface Builder using Auto Layout

I have an existing UILabel that I created in Interface Builder, I would like to change its width in code, but I can't because of the auto layout. It's pretty simple, I have width from a CGSize and I wanna set it for the label. Actually my code works perfectly, I can assign the new size to the label, but unfortunately it doesn't redrawn itself. I've tried to use the textRectForBounds:limitedToNumberOfLines:and preferredMaxLayoutWidth without any success or size changes.
float heightIs =
[cell.lbl.text
boundingRectWithSize:cell.lbl.frame.size
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{ NSFontAttributeName:cell.lbl.font }
context:nil]
.size.height;
// get the width size of a string
CGSize textSize = [cell.lbl.text sizeWithAttributes:#{NSFontAttributeName:cell.lbl.font}];
CGFloat strikeWidth = textSize.width;
NSLog(#"TEXT WIDTH %f OF STRING %#", strikeWidth, nameString);
CGRect labelFrame = CGRectMake (0, 0, strikeWidth, heightIs);
cell.lbl.frame = labelFrame;
cell.lbl.preferredMaxLayoutWidth = CGRectGetWidth(labelFrame);
NSLog(#"LABEL WIDTH VALUE %f", cell.lbl.frame.size.width);
Could somebody explain me the right way? I'm not sure that where should I start it. Is it an option somewhere in IB or can I do it with code? Or I can delete all code because it can be done only with IB?

ScrollView can't fit it's subview's content sometimes

I'm trying to let the user to adjust himself the font size to read the content of the app. therefor i put a slider that if the user swipe right, the fonts will grow and left means that the fonts size will be smaller. it works fine, but the problem is that sometimes the scrollView content size is not getting the new content size.
This is my method:
- (IBAction)enlargeLabelWithSlider:(id)sender{
UISlider *slider = (UISlider *)sender;
int font = 0;
int currentSliderValue = (int)slider.value;
if (currentSliderValue<=lastSilderValue) /* Every time the method call, at the end lastSilderValue = currentSliderValue*/
{
// Need to increase
font =lastSilderValue - currentSliderValue;
[self.gameTitleLabel setFont:[UIFont fontWithName:self.gameTitleLabel.font.fontName size:self.gameTitleLabel.font.pointSize+font]];
[self.gameScoreLabel setFont:[UIFont fontWithName:self.gameScoreLabel.font.fontName size:self.gameScoreLabel.font.pointSize+font]];
self.gameStateLabel.font = [UIFont systemFontOfSize:self.gameStateLabel.font.pointSize+font];
}
else
{
// Need to decrease
font =currentSliderValue - lastSilderValue;
[self.gameTitleLabel setFont:[UIFont fontWithName:self.gameTitleLabel.font.fontName size:self.gameTitleLabel.font.pointSize-font]];
[self.gameScoreLabel setFont:[UIFont fontWithName:self.gameScoreLabel.font.fontName size:self.gameScoreLabel.font.pointSize-font]];
self.gameStateLabel.font = [UIFont systemFontOfSize:self.gameStateLabel.font.pointSize-font];
}
lastSilderValue = currentSliderValue;
CGFloat height = self.gameStateLabel.frame.origin.y+self.gameStateLabel.frame.size.height+20;
CGSize size = CGSizeMake(self.ScrollView.frame.size.width, height);
self.ScrollView.contentSize = CGSizeMake(size.width, size.height); // i used self.gameStateLabel.frame.origin.y because it's the last label on the view.
}
can someone tell me why is this happening? Thanks.
I don't see any change to the UILabel frame.
Maybe you have to adapt this frame to the new font size and then try to modify the scrollview contentSize property.
This will be helpful: Adjust UILabel height depending on the text

Adjusting the height of the UITextField with editing using iOS Autolayout

How do we increase the height of UITextField while editing using autolayout. I have a UIScrollView with four UITextField's. Currently all the textfield's are all of constant height. I need only a particular textfield to grow its height based on the text while editing.
You need to set height constrain for each text field.
And on edit did end method you need to identify the textfield by tag and than change the constant of the appropriate textfield.
for ex. heightTxt1,heightTxt2,heightTxt3,heightTxt4 are constraint.
Than change while edit did end called for textfield 1
heightTxt1.constant= (count height on the basis of text and font style,size);
This should resolve your issue,
Step 1: Set no of lines in your label as 0
Step 2: Add this method in your class file
//-- Dynamic label frame depend on text
-(CGRect)getLabelHeightForIndex:(UILabel *)label label_string:(NSString *)label_string
{
CGSize maxSize = CGSizeMake(label.frame.size.width, 999);
CGRect contentFrame;
CGSize contentStringSize;
NSString *version = [[UIDevice currentDevice] systemVersion];
NSString *contentStr = label_string;
if ([version floatValue] < 7.0)
{
contentStringSize = [contentStr sizeWithFont:label.font constrainedToSize:maxSize lineBreakMode:label.lineBreakMode];
}
else
{
NSDictionary *contentDic = [NSDictionary dictionaryWithObjectsAndKeys:label.font, NSFontAttributeName, nil];
contentStringSize = [contentStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:contentDic context:nil].size;
}
contentFrame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, contentStringSize.height);
return contentFrame;
}
Step 3: Access dynamic frame for label using following code
//-- Get dynamic label height from given string
CGRect contentFrame = [self getLabelHeightForIndex:Label label_string:Label.text];
Label.frame = contentFrame;
CGFloat LabelHeight = contentFrame.size.height;
First off, you will want to store the height constraint for that specific UITextField in a property.
For example: #property (nonatomic, weak) IBOutlet NSLayoutConstraint *specificTextFieldHeightConstraint;
Then, implement -[UITextFieldDelegate textFieldDidBeginEditing:] inside your UIViewController subclass:
- (void)textFieldDidBeginEditing:(UITextField *)textField {
specificTextFieldHeightConstraint.constant = expandedHeightGoesHere;
}
Finally, you probably want to return the height back to normal by implementing -[UITextFieldDelegate textFieldDidEndEditing:] inside your UIViewController subclass:
- (void)textFieldDidEndEditing:(UITextField *)textField {
specificTextFieldHeightConstraint.constant = originalHeightConstant;
}
If you set equal heights constraints across all of the UITextFields, you will need to set the priority of the equal height constraint that is attached to specificTextField to low when editing, and set it back to high when editing ends. You will still need a height constraint on specificTextField, but it should have a lower priority than the equal height constraint when specificTextField is not editing, and it should have a higher priority than the equal height constraint when specificTextField is editing.

Adding additional space to UILabel to insert image

I have an issue with adding image in the end of the text of the UILabel. How can I detect the size of the text in the label, then add additional space and insert image into it?
i write a little code for this:
-(void) labelSizeGetter
{
UILabel * mylabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
float heigth=25.0;//max height value of label.
NSString *yourString = #"My great text";
mylabel.font =[UIFont fontWithName:#"Helvetica-Bold" size:12];
[mylabel setText:yourString];
CGSize s = [mylabel.text sizeWithFont:[UIFont systemFontOfSize:12]
constrainedToSize:CGSizeMake(MAXFLOAT,heigth)
lineBreakMode:NSLineBreakByWordWrapping];
// s is a size for text of label. just add 10 pix to width to make it more beautiful.
NSLog(#"%#", NSStringFromCGSize(s));
mylabel.frame=CGRectMake(0, 0, s.width+10, s.height);
[self.view addSubview:mylabel];
UIView * myimage=[[UIView alloc] initWithFrame:CGRectMake(mylabel.frame.origin.x+mylabel.frame.size.width , mylabel.frame.origin.y, 30, 30)];//create your images frame according to frame of your label
myimage.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:#"arti.png"]];
[self.view addSubview:myimage];
}
i hope it helps
Best Way is take one UIView.
And Add Both UILabel And UIImageView on This UIView (give Fram as per your Requirement).
And This UIView to your MainView of UIViewController.
If you dont want to use a UIView. Why not check the length of the string in the label. then add some additional space for your image using frame. [UILabel.text length] returns the length.
Create some container UIView if you need or just use superview
Put there UILabel and UIImageView
Calculate a size of the text using [NSString sizeWithFont:] or similar sizeWith... method
Calculate position of your UIImageView according to a size of the text
Here is a code snippet which gives you size adjustable for specific font and specific font size. Accordingly you can set frame for your label and then image view as well.
- (CGSize)getSizeFromText:(NSString*)text {
CGSize constrainedSize;
constrainedSize.width = give maximum allowable width limit;
constrainedSize.height = MAXFLOAT;
CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:fontSize] constrainedToSize:constrainedSize lineBreakMode: UILineBreakModeWordWrap];
return size;
}
Hope this would help you to solve your problem.
There is a category on NSString that returns the size of a string when rendered with a given font. There are several methods, the most complete on being - (CGSize)sizeWithFont:(UIFont *)font minFontSize:(CGFloat)minFontSize actualFontSize:(CGFloat *)actualFontSize forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode (see Apple Docs).
With that information you might be able to achieve what you want to do.

UILabel - auto-size label to fit text?

Is it possible to auto-resize the UILabel box/bounds to fit the contained text?
(I don't care if it ends up larger than the display)
So if a user enters "hello" or "my name is really long i want it to fit in this box", it is never truncated and the label is 'widened' accordingly?
Please check out my gist where I have made a category for UILabel for something very similar, my category lets a UILabel stretch it's height to show all the content: https://gist.github.com/1005520
Or check out this post: https://stackoverflow.com/a/7242981/662605
This would stretch the height, but you can change it around easily to work the other way and stretch the width with something like this, which is I believe what you want to do:
#implementation UILabel (dynamicSizeMeWidth)
- (void)resizeToStretch{
float width = [self expectedWidth];
CGRect newFrame = [self frame];
newFrame.size.width = width;
[self setFrame:newFrame];
}
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize maximumLabelSize = CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX);
CGSize expectedLabelSize = [[self text] sizeWithFont:[self font]
constrainedToSize:maximumLabelSize
lineBreakMode:[self lineBreakMode]];
return expectedLabelSize.width;
}
#end
You could more simply use the sizeToFit method available from the UIView class, but set the number of lines to 1 to be safe.
iOS 6 update
If you are using AutoLayout, then you have a built in solution. By setting the number of lines to 0, the framework will resize your label appropriately (adding more height) to fit your text.
iOS 8 update
sizeWithFont: is deprecated so use sizeWithAttributes: instead:
- (float)expectedWidth{
[self setNumberOfLines:1];
CGSize expectedLabelSize = [[self text] sizeWithAttributes:#{NSFontAttributeName:self.font}];
return expectedLabelSize.width;
}
Using [label sizeToFit]; will achieve the same result from Daniels Category.
Although I recommend to use autolayout and let the label resize itself based on constraints.
If we want that UILabel should shrink and expand based on text size then storyboard with autolayout is best option. Below are the steps to achieve this
Steps
Put UILabel in view controller and place it wherever you want. Also put 0 for numberOfLines property of UILabel.
Give it Top, Leading and Trailing space pin constraint.
Now it will give warning, Click on the yellow arrow.
Click on Update Frame and click on Fix Misplacement. Now this UILabel will shrink if text is less and expand if text is more.
This is not as complicated as some of the other answers make it.
Pin the left and top edges
Just use auto layout to add constraints to pin the left and top sides of the label.
After that it will automatically resize.
Notes
Don't add constraints for the width and height. Labels have an intrinsic size based on their text content.
Thanks to this answer for help with this.
No need to set sizeToFit when using auto layout. My complete code for the example project is here:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var myLabel: UILabel!
#IBAction func changeTextButtonTapped(sender: UIButton) {
myLabel.text = "my name is really long i want it to fit in this box"
}
}
If you want your label to line wrap then set the number of lines to 0 in IB and add myLabel.preferredMaxLayoutWidth = 150 // or whatever in code. (I also pinned my button to the bottom of the label so that it would move down when the label height increased.)
If you are looking for dynamically sizing labels inside a UITableViewCell then see this answer.
Use [label sizeToFit]; to adjust the text in UILabel
Here's what I am finding works for my situation:
1) The height of the UILabel has a >= 0 constraint using autolayout. The width is fixed.
2) Assign the text into the UILabel, which already has a superview at that point (not sure how vital that is).
3) Then, do:
label.sizeToFit()
label.layoutIfNeeded()
The height of the label is now set appropriately.
I created some methods based Daniel's reply above.
-(CGFloat)heightForLabel:(UILabel *)label withText:(NSString *)text
{
CGSize maximumLabelSize = CGSizeMake(290, FLT_MAX);
CGSize expectedLabelSize = [text sizeWithFont:label.font
constrainedToSize:maximumLabelSize
lineBreakMode:label.lineBreakMode];
return expectedLabelSize.height;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label
{
CGRect newFrame = label.frame;
newFrame.size.height = [self heightForLabel:label withText:label.text];
label.frame = newFrame;
}
-(void)resizeHeightToFitForLabel:(UILabel *)label withText:(NSString *)text
{
label.text = text;
[self resizeHeightToFitForLabel:label];
}
#implementation UILabel (UILabel_Auto)
- (void)adjustHeight {
if (self.text == nil) {
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.bounds.size.width, 0);
return;
}
CGSize aSize = self.bounds.size;
CGSize tmpSize = CGRectInfinite.size;
tmpSize.width = aSize.width;
tmpSize = [self.text sizeWithFont:self.font constrainedToSize:tmpSize];
self.frame = CGRectMake(self.frame.origin.x, self.frame.origin.y, aSize.width, tmpSize.height);
}
#end
This is category method. You must set text first, than call this method to adjust UILabel's height.
You can size your label according to text and other related controls using two ways-
For iOS 7.0 and above
CGSize labelTextSize = [labelText boundingRectWithSize:CGSizeMake(labelsWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:#{
NSFontAttributeName : labelFont
}
context:nil].size;
before iOS 7.0 this could be used to calculate label size
CGSize labelTextSize = [label.text sizeWithFont:label.font
constrainedToSize:CGSizeMake(label.frame.size.width, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
// reframe other controls based on labelTextHeight
CGFloat labelTextHeight = labelTextSize.height;
If you do not want to calculate the size of the label's text than you can use -sizeToFit on the instance of UILabel as-
[label setNumberOfLines:0]; // for multiline label
[label setText:#"label text to set"];
[label sizeToFit];// call this to fit size of the label according to text
// after this you can get the label frame to reframe other related controls
Add missing constraints in storyboard.
Select UILabel in storyboard and set the attributes "Line" to 0.
Ref Outlet the UILabel to Controller.h with id:label
Controller.m and add [label sizeToFit]; in viewDidLoad
the sizeToFit() method doesn't play well with constraints, but as of iOS 9 this is all you need -
label.widthAnchor.constraint(equalToConstant: label.intrinsicContentSize.width).activate()
I had a huge problems with auto layout.
We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
Fits everytime! :)
name.text = #"Hi this the text I want to fit to"
UIFont * font = 14.0f;
CGSize size = [name.text sizeWithAttributes:#{NSFontAttributeName: font}];
nameOfAssessment.frame = CGRectMake(400, 0, size.width, 44);
nameOfAssessment.font = [UIFont systemFontOfSize:font];
you can show one line output then set property Line=0 and show multiple line output then set property Line=1 and more
[self.yourLableName sizeToFit];
There's also this approach:
[self.myLabel changeTextWithAutoHeight:self.myStringToAssignToLabel width:180.0f];

Resources