UILabel sizeToFit method not working properly - ios

I'm trying to show a long chunk of text inside a UILabel in one line.
The UILabel is a subview of UIScrollView so I can scroll and see the entire UILabel.
My problem is that the sizeToFit method only partialy works.
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 1;
[textLabel sizeToFit];
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
The UIScrollView content size gets big enough to show the entire UILable, but for a line like:
so i'll try to share some of them here every once in a while."
The UILabel shows:
so i'll try to share som...
What am I doing wrong?

Turns out the code is just fine - but the Use Autolayout was checked.
Unchecked it - everything works just great...

If you want to achieve this with auto layout turned on it's simple. Just make sure you add numberOfLines
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.numberOfLines = 0;

Surprisingly, if you did not put a constraint on the label's width, this would work:
[textLabel.superview layoutSubviews];
I learned this by trial and error.

try
textLabel.adjustsFontSizeToFitWidth = YES;
textLabel.minimumFontScale = 0.5;

Since you have restricted your Label to show only one line of Text and truncate the rest , it is behaving the same
textLabel.attributedText = attributedString;
textLabel.numberOfLines = 0;
[textLabel sizeToFit];
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textScrollView.contentSize = CGSizeMake(textLabel.frame.size.width, textLabel.frame.size.height);
Hope it will help you

The most common reason for sizeToFit not working properly is the UILabel not having any autolayout constraints, for instance if you're implicitly relying on the view position remaining fixed relative to the top left. Adding any constraint at all (leading, top, centerY, anything) will fix it, presumably because it will result in layoutSubviews being called at some point, as suggested in Maxthon Chan's answer.

Related

UILabel text always has a line break

Screenshot of the issue:
self.label.text = #"回复111111111111111111111111111111111111111";
I wrote the code to set the text of label, but the label always has a line break right after the "回复". Can someone help me to get this text to display all in one line?
You can use the sizeToFit property of a UILabel to adjust the height as per the text. Once you set the text, you can simply call:
[yourLabel sizeToFit];
You can set UILabel like this :
this code will adjust your font size according to your label width.
label.adjustsFontSizeToFitWidth = true

Dynamically Sized UILabel Followed Directly by UIButton

How can I position a UIButton right at the end of a dynamic UILabel?
Here is a screenshot of what I'm trying to achieve:
Are you using Autolayout? If so, add horizontal spacing constraint and baseline alignment constraint between the label and the button. Make sure also that numbers of lines of the label is 0.
Try
[your_label sizeToFit];
CGRect rect = your_button.frame;
rect.origin.x = CGRectGetMaxX(your_label.frame);
your_button.frame = rect;
I'd override -[UIView layoutSubviews] and do what you want there. Once you do that, the code will look something like Avt's answer. If you want the label to have multiple lines, but a constrained width, you may want to try something like
CGSize labelSize = [yourLabel sizeThatFits:CGSizeMake(someWidth, 9999)];
and use that to set the label's frame.
If you want the button to appear at the bottom of the UILabel, use constrains.

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.

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.

Multiline UILabel from xib

In my awakeFromNib function, I have:
[_descriptionLabel setLineBreakMode:UILineBreakModeWordWrap];
[_descriptionLabel setNumberOfLines:10];
[_descriptionLabel sizeToFit];
and yet my label looks like this:
I know I'm setting these calls on the right label, because without these lines, the text appears vertically centered rather than aligned at the top. How can I make make my UILabel multiline?
I also tried setNumberOfLines:0.
SOLUTION I had set the width incorrectly in the xib file.
Try to set [_descriptionLabel setNumberOfLines:0]; which set the number of lines to auto.
It might be that sizeToFit is changing your label width, try to set it to explicit width, or remove it.
Just make sure that the initial width is set correctly. Then it should expand/shrink the height. But still the label won't be aligned to the top, it will be centered in its previous size after a call of sizeToFit (in case the new height is smaller than before, otherwise the origin will stay the same).
If you're not using AutoLayout, you need to measure text in code:
CGRect frame = _descriptionLabel.frame;
CGSize size = [_descriptionLabel.text sizeWithFont:_descriptionLabel.font constrainedToSize:CGSizeMake(frame.size.width, FLOAT_MAX) lineBreakMode:_descriptionLabel.lineBreakMode];
frame.size.height = MIN(MAX(size.height, frame.size.height), MAX_ALLOWED_HEIGHT);
_descriptionLabel.frame = frame;
Are you sure your awakeFromNib is in the right place. If it's in the view controller, it won't work. If it's in the implementation of a custom label, it should get called and that code should work:
#interface TestLabel : UILabel
#end
#implementation TestLabel
- (void)awakeFromNib
{
[self setLineBreakMode:UILineBreakModeWordWrap];
[self setNumberOfLines:10];
[self sizeToFit];
NSLog(#"Label: %#", NSStringFromCGRect(self.frame));
}
#end
Also, it's easier to set numberOfLines to 0, which means "any number of lines". And you shouldn't need to set UILineBreakModeWordWrap, since that's the default.
If you want to keep the code in the view controller, you can move it to viewDidLoad, which is the best place to do this kind of setup.

Resources