Adjust width of UILabel based on its contents - ios

I had a look on SO before asking this question. All the questions are about adjusting the height of a UILabel and not its width. I tried alternative methods but it did not work such as [label sizeToFit];. Is it possible to adjust the width of a label based on its text? I create my label in a UITableViewCell in story board. I want to be able to adjust its width based on the text that it is assigned. I dont want to resize the font size.
I set the text of the label in CellForRowAtIndexPath.
Examples would be great please.
Thanks in advance :)
Update 1: I have a custom cell that I am making in Storyboard so not programmatically. I set the contents of each cell in CellForRowAtIndexPath, for example, myLabel.text = recipe.name. The name label is quite small, however I would like to extend its width based on the length of the text, not truncate the tail or shrink the size of the text.
Update2: I have a lot of other UIElements in the cell. So I have a label in the top left, top right, bottom left, bottom right, and a picture in the middle, there default is 120 because they have a background color. I set it small the there is not a huge amount of empty space in the label.

Get the size of the string:
//Replace FLT_MAX with the maximum height/width you want the label to be, if no maximum leave as FLT_MAX.
CGSize stringSize = [YOUR_STRING sizeWithFont:YOUR_FONT constrainedToSize:CGSizeMake(FLT_MAX, FLT_MAX) lineBreakMode:NSLineBreakByWordWrapping];
Then size your label:
[YOUR_LABEL setFrame:CGRectMake(0, 0, stringSize.width, stringSize.height)];
In iOS 7 sizeWithFont is deprecated, use boundingRectWithSize instead:
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:YOUR_LABELS_FONT
forKey: NSFontAttributeName];
CGSize stringSize = [text boundingRectWithSize:CGSizeMake(FLT_MAX, FLT_MAX)
options:NSStringDrawingTruncatesLastVisibleLine |
NSStringDrawingUsesLineFragmentOrigin
attributes:stringAttributes context:nil].size;

CGSize maxSize = CGSizeMake(250, CGFLOAT_MAX); //250 is max desired width
CGSize textSize = [Label.text sizeWithFont:Label.font constrainedToSize:maxSize];
Label.frame = CGRectMake(0, 0, textSize.width, 15); // desired Bounds
Using above code you can get frame size for perticular text, & then resize label accordingly

You don't need to set explicit width for UILabel. UILabel provides intrinsic content size when used with autolayout. If you add constraints that provide the label's x,y position(Top Space constraint + Leading Space constraint), autolayout will be able to determine its width height based on the content.

Related

Make UILabel height zero if label empty/storyboard

I have a lot of labels stacked up for a contact info screen. If any of the labels are empty, I would love to zero out their height and have them occupy no space to avoid empty space on the screen. However, I have created the screen in storyboard and the labels have been assigned heights and y values.
Here is code I've been trying to use to alter label height but cannot get it to work. Perhaps it is designed to work only for labels created programmatically and the storyboard settings override what I am doing here.
NSString *string = #"some text";
CGSize maximumLabelSize = CGSizeMake(280,1000);
 
// use font information from the UILabel to calculate the size
CGSize expectedLabelSize = [string sizeWithFont:myLabel.font constrainedToSize:maximumLabelSize lineBreakMode:NSLineBreakByWordWrapping];
 
// create a frame that is filled with the UILabel frame data
CGRect newFrame = myLabel.frame;
// resizing the frame to calculated size
newFrame.size.height = expectedLabelSize.height;
// put calculated frame into UILabel frame
myLabel.frame = newFrame;
Is there a way to get the height of labels created in storyboard to zero out if they are empty?
you can override the following method of the view containing your label and do something like that:
-(void) layoutSubviews {
myLabel.frame = CGRectZero;
}
This method is in order to allow to layout the subviews or you view. Now I don't know If you have used contraints to define the height of your label. If so you should change in the same way the height of your label. Note the in the above example I used CGRectZero.

UILabel Font and height in IOS

I see that UILabel in IOS has height property along with font . I also see that if I give the height and font same value, for some characters the text gets cut in UILabel. How are these two different? While doing the UI design if height is more than the font size, there would be some extra white space which is what I want to avoid and hence wanted to know what exactly is the difference between the two.
You can use sizeThatFits: to determine correct height for UILabel
UILabel *label;
label.text = #"Some text";
CGRect labelFrame = label.frame;
labelFrame.size.height = [label sizeThatFits:CGSizeMake(labelFrame.size.width), MAXFLOAT].height;
label.frame = labelFrame;
The text size is the height from the font's baseline to its cap line, which doesn't take into consideration descenders (like on the letters 'g' and 'y') or ascenders (like 'f', in some fonts). In general, you don't have to (or even need to) set a label's height; it determines the best height based on its font size.
See https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/CustomTextProcessing/CustomTextProcessing.html for details about how font sizes work.

How to limit max width of UILabel?

There are a UILabel in the center of the UIView, named nicknameLabel, and will append a gender image after the nicknameLabel.
But when the nicknameLabel has a lot of text, it will beyond the bounds of the UIView.
So, how to limit max width of UILabel?
BTW: I using the storyboard. Thanks.
Give the label a <= constraint like this:
use following code and set your width in boundingRectWithSize value.
CGSize itemTextSize = [#"Your Text" boundingRectWithSize:CGSizeMake(100, 30) options:NSStringDrawingUsesLineFragmentOrigin attributes:#{NSFontAttributeName : [UIFont fontWithName:#"Helvetica Neue" size:12.5]} context:nil].size;
If you are using constraints then remove all constraints from you label.
Then again set frames of your label and if you want to make multiline label, then simply set the number of lines from 1 to 0 and increase the height of your label.
OR
If you want to fit your text within the label.You can simply enable Autoshrink property.

Vertically Center UILabel Size Resized Font

I have a UIlabel with constraints set. Constraint to both left and right sides and vertical center were set to the label. The parent view width is dynamic, means can be wider or not but the height is static. The label will be set with some text that are long or short.
I also set the minimum font size so that the font would not wrap and set it to one line only. Since I set the minimum font size, the text height auto adjusts to fit the text but the problem the text is not centered vertically instead it sits at the bottom of the UIlabel.
I tried to resize the height of the UIlabel but I can't get it to resize with the right size based on the new font size and when to set the new size. I tried the solutions here by getting the font size and setting the height dynamically instead it caused unexpected results. I am running it on iOS 6.
I figured it out myself. Below is a sample code
+(void)autoFontResizeLabel:(UILabel*)label inView:(UIView*)containerView{
NSString *text = label.text;
//determine the font size
CGFloat actualFontSize;
[text sizeWithFont:label.font
minFontSize:18
actualFontSize:&actualFontSize
forWidth:label.bounds.size.width
lineBreakMode:label.lineBreakMode];
//reset the label content and frame
[label setText:#""];
[label setText:text];
//turn off auto adjust to allow new text with correct font
label.adjustsFontSizeToFitWidth = NO;
[label setFont:[UIFont fontWithName:#"HelveticaNeue" size:actualFontSize]];
//optional
[label sizeToFit];
CGSize barSize = containerView.frame.size;
CGFloat titleY = fabsf(barSize.height - label.frame.size.height)/2;
[label setFrame:CGRectMake(label.frame.origin.x, titleY, label.frame.size.width, label.frame.size.height)];
}

UIlabel shows extra space before text

I have used UILabel in my app. It is working properly in portrait mode. But when I open my app in landscape mode it shows content in center of UIlabel. I have tried sizeToFit but it is not working. As soon as I increase uilabel's width spacing starts to arrive in uilabel.
My code:
self.contentLabel.text = labeltext;
[self.contentLabel setNumberOfLines:0];
[self.contentLabel sizeToFit];
I suspect your UILabel itself and not the text within it is actually aligning incorrectly upon rotation. Make sure the label stays aligned to the top of the view. Try:
self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight;
or
self.contentLabel.autoresizingMask = UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
Edit: One other thought.
If auto layout's enabled and you're calling sizeToFit in viewDidLoad, perhaps the view is resizing after auto layout lays out the subviews. Try putting your code in viewDidLayoutSubviews instead.
If you add a UILabel with height bigger than the height of the text, it's normal if that happened and there is no way to change this alignement (Vertical center).
I have two solutions for this problem:
Work with constraint :
This constraint Greater than or equal is just magic.
If you create the label with the code I suggest to work with that:
UIFont *fontReceive = [UIFont systemFontOfSize:[UIFont systemFontSize]];
CGSize sizeText = [text sizeWithFont:fontReceive constrainedToSize:CGSizeMake(260, 9999) lineBreakMode:NSLineBreakByWordWrapping];
Hope that will help!
The best solution is to change the height of your cell according the the amount of text your are populating it with.
Please see this code below as an example.
NSString *content = **YOUR_STRING_LABEL_INTENDED_CONTENT**
CGSize maximumLabelSize = CGSizeMake(390, 1000); //For example - Put in your desired label width here and maximum size etc.
NSDictionary *stringAttributes = [NSDictionary dictionaryWithObject:[UIFont systemFontOfSize:13] forKey: NSFontAttributeName]; //This allows a calculation to be made of the space taken up, so if you're using a custom or large font it will calculate accordingly.
CGSize newExpectedLabelSize = [content boundingRectWithSize:maximumLabelSize options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin attributes:stringAttributes context:nil].size;
Now you can change the height of your label by using this next line, where label is the name of the label you made.
GCRect frame = label.frame;
frame.size.height = newExpectedLabelSize.height;
label.frame = frame;
I hope this helps, cheers, Jim.

Resources