简体   繁体   中英

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. It leaves the text of my UILabel in the centre. 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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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