为什么当我尝试更改高度以适合文本时,我的 UILabel 添加了这么多额外的 space?

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

我不知道为什么我的UILabel身高会膨胀到这么高。它在中间留下了我的 UILabel 的文本。我不想要所有这些额外的 space...

不需要的额外内容space

这是我的代码(我在这之前设置了文本):

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

请帮忙 :( 我只想 UILabel 的高度正好适合文本。

试试这个:

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)

请检查 this answer 它对我有用,这正是你要找的。

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

先设置边框,再调整尺寸以适应标签。

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