Question

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];
Was it helpful?

Solution

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.

OTHER TIPS

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).

enter image description here

I have two solutions for this problem:

Work with constraint :

enter image description here

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top