UIlabel shows extra space before text - ios

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.

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.

Adjust width of UILabel based on its contents

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.

Change label height in tableview in iOS 7

I have a label in custom cell in table view.
I want to change cell height and also label height(at first I am showing only 2 line, I want to show more text) after user taped a cell,
I am able to change cell height based on cell content, but unfortunately I cannot change label height, :((
I've read tons of stackoverflow answers, but still nothing.
it is believed that this would work:
CGSize labelSize = [#"Hello World!" sizeWithFont:[UIFont systemFontOfSize:17] constrainedToSize:CGSizeMake(label.frame.size.width,MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];
but this is deprecated in iOS 7; can any one please help me in resizing my label in cell?
If you want the height of your label relative to the height of your cell and you use Storyboard, you should determine the size of your label with constraints in relation to the ContentView of the cell. Just set the top and bottom distance from your label to the ContentView and no additional height for the label.
If you dont know how to set Storyboard and constraints, this might help: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutbyExample/AutoLayoutbyExample.html
UITableViewCell lays out it's content in -layoutSubviews. Therefore, if you want to simply have a custom layout logic, you need to subclass UITableViewCell and override the -layoutSubviews method. It's a good idea to call super anyway before applying your logic, though.
You may use something like this to get UIlabel size
-(CGFloat)getLabelSize:(UILabel *)label fontSize:(NSInteger)fontSize
{
NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[UIFont systemFontOfSize:fontSize], NSFontAttributeName,
nil];
CGRect frame = [label.text boundingRectWithSize:CGSizeMake(270, 2000.0)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:attributesDictionary
context:nil];
CGSize size = frame.size;
return size.height;
}

Autoresize view to fit multiline label with dynamic text length

I have a UIView containing a UILabel made in an Interface Builder .xib file. The label text is set from code and I want the UIView and UILabel to resize to fit the text using auto layout.
Label configuration:
Pinned width 320
Number of lines 0
Leading space to superview 0
Bottom space to superview 0
Trailing space to superview 0
The view is loaded like this:
MyView *myView = [[[NSBundle mainBundle] loadNibNamed:#"MyView" owner:self options:nil] objectAtIndex:0];
myView.myLabel.text = #"My short or long text";
and I use it as a table header:
[self.tableView setTableHeaderView:myView];
The view does not resize, it stays one line truncated with ... at the end. How do I get it to resize?
I tried increasing vertical content hugging and content resistance for the label, I tried adding a low priority height constraint, I tried setPreferredMaxLayoutWidth, all without luck.
Note: This is a simplified example. I will need more elements in the view, and I would like to avoid calculating every coordinate manually based on the label's sizeWithFont. It's my understanding that auto layout should be the holy grail for this.
CGSize maximumSize = CGSizeMake(maxWidthOfYourLabel, 9999);
UIFont *myFont = label.font;
CGSize myStringSize = [yourString sizeWithFont:myFont constrainedToSize:maximumSize lineBreakMode:NSLineBreakByWordWrapping];
label.frame = CGRectMake (label.frame.origin.x, label.frame.origin.y, myStringSize.width, myStringSize.height);
yourView.height = label.height;
This is the only way i know and this involves sizeWithFont:
I doubt UITableView will play nicely with your view if you are resizing its header with autolayout. The way we work with dynamic-sized table headers (or footers) is like this:
Compute and resize the header view's frame.
Re-set the header via self.tableView.tableHeaderView = myView;
Step 2 is the key. You have to set tableHeaderView again even if the same view will be applied. I understand that having to play with frames in an autolayout paradigm is very ugly, but you may not have to if you find the proper method to put self.tableView.tableHeaderView = myView;.
I just come across the same problem like you.
What I do is like this:
//Init headerView from nib file
//Set the content to show
[headerView setupWith:somethingToShow];
headerView.height = [headerView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
self.tableView.tableHeaderView = headerView;

UITextView can't change size with auto layout

I have a XIB file containing a view with a UITextView as subview. This textView is 30px high, because it should resize according to it's content.
So I set the text programmatically, call -sizeToFit and reconfigure the frame of the textView and its superview:
[_textView setText:[contents objectForKey:#"body"]];
[_textView sizeToFit];
CGSize txtSize = _textView.contentSize;
txtSize.height = _textView.frame.size.height;
_textView.contentSite = txtSize;
CGRect superFrame = _textView.superView.frame;
superFrame += _textView.contentSize.height;
_textView.superView.frame = superFrame;
The superView actually does resize correctly. Also, when logging the text views frame and content size, on the console it appears to be okay (about 1200px high).
But the textView is still just 30px high on the screen. Also calling -setNeedsLayout did not do the trick.
What could be the issue here?
This is a bug i ran into a couple of days ago. It seems that UITextView will cut off a part of the text no matter the height if its scroll is disabled.
A solution that works in certain situations is:
[_textView setScrollEnabled:YES];
[_textView setText:text];
[_textView setScrollEnabled:NO];
I have reported this bug to Apple, but I suggest you do the same.

Resources