0

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.

Nilesh
  • 701
  • 5
  • 14
JessThePest
  • 155
  • 2
  • 11

3 Answers3

2

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];**
Jaimish
  • 629
  • 5
  • 15
1

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)

Community
  • 1
  • 1
Islam
  • 3,654
  • 3
  • 30
  • 40
0

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;
Community
  • 1
  • 1
Burhan Ahmad
  • 728
  • 5
  • 13