UIlabel shows extra space before text

守給你的承諾、 提交于 2019-12-10 18:33:26

问题


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];

回答1:


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.




回答2:


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!




回答3:


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.



来源:https://stackoverflow.com/questions/21847010/uilabel-shows-extra-space-before-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!