简体   繁体   English

当我尝试更改高度以适合文本时,为什么要在UILabel中添加这么多额外的空间?

[英]Why is so much extra space being added to my UILabel when I try to change height to fit text?

I have no idea why the height of my UILabel is expanding to such a great height. 我不知道为什么我的UILabel的高度会扩展到如此之高。 It leaves the text of my UILabel in the centre. 它将我的UILabel的文本放在中间。 I don't want all of this extra space... 我不要所有这些多余的空间...

Unwanted extra space 多余的空间

Here is my code (I set the text before this point): 这是我的代码(我在此之前设置了文本):

self.infoDescription.numberOfLines = 0;
[self.infoDescription sizeToFit];
self.infoDescription.frame = CGRectMake(20, self.infoAdultSize.frame.size.height+self.infoAdultSize.frame.origin.y+10, self.infoView.frame.size.width-40, self.infoDescription.frame.size.height);

Please help :( I just want the height of the UILabel to fit the text exactly. 请帮助:(我只希望UILabel的高度完全适合文本。

First set the frame and then make size to fit of label. 首先设置框架,然后调整尺寸使其适合标签。

  **self.infoDescription.frame = CGRectMake(20, self.infoAdultSize.frame.size.height+self.infoAdultSize.frame.origin.y+10, self.infoView.frame.size.width-40, self.infoDescription.frame.size.height);
    [self.infoDescription sizeToFit];**

Try this: 尝试这个:

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont 
                           constrainedToSize:maximumSize 
                               lineBreakMode:self.myLabel.lineBreakMode];

( original source ) 原始资料

Please check this answer it works for me and it is exactly what you are looking for. 请检查此答案对我有用,而这正是您所需要的。

//Calculate the expected size based on the font and linebreak mode of your label
// FLT_MAX here simply means no constraint in height
CGSize maximumLabelSize = CGSizeMake(296, FLT_MAX);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font constrainedToSize:maximumLabelSize lineBreakMode:yourLabel.lineBreakMode];   

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM