views:

265

answers:

3

I know there is this one:

sizeWithFont:minFontSize:actualFontSize:forWidth:lineBreakMode:

But since the CGSize always has the same height and doesn't adjust to any shrinked text or whatsoever, the CGSize is not telling how heigh the text is.

Example: Make a UILabel with 320 x 55 points and put a loooooooooooooong text in there. Let the label shrink the text down. Surprise: CGSize.height remains the same height even if the text is so tiny that you need a microscope.

Ok so after banging my head against my macbook pro which is half way broken now, the only think that can help is that nasty actualFontSize. But the font size is in pica I think, it's not really what you get on the screen, isn't it?

When that font size is 10, is my text really 10 points heigh at maximum? Once in a while I tried exactly that, and as soon as the text had a y or some character that extends to below (like that tail of an y does), it is out of bounds and the whole text is bigger than 10 points.

So how would you calculate the real text height for a single line uilabel without getting a long beard and some hospital experience?

+3  A: 

Try this code:

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

from my answer here

It uses a different method, and sets up a very high CGSize at the start (which is then shrunk to fit the string)

nevan
Well, but I do want the text to be pressed down to fit in a small rectangle...
dontWatchMyProfile
Tried, but it doesnt work. When the text gets shrinked down by the label, the height remains the same. I also tried to provide the rect of the labels frame as the maximumSize.
dontWatchMyProfile
Have you set `adjustsFontSizeToFitWidth` to prevent the font size from getting smaller? Or do you want the size to shrink with the label?
nevan
yes, I do want that the label shrinks the font size to fit the width. And in case it is shrinked, I need to know the height of that shrinked text...
dontWatchMyProfile
+1  A: 

Also have you set label.numberOfLines = 0; ?

Skie
no, but is that important to do? also, why 0? isn't that at least 1 line?
dontWatchMyProfile
This property sets max possible number of showed lines. 1 is default value. 0 mean that label will not restrict number of lines.
Skie
A: 

Sounds like after you get the actual font size from that function call, you need to call again with that new size:

NSString* yourString = @"SomeString";
float actualSize;
[yourString sizeWithFont:yourFont 
             minFontSize:minSize 
          actualFontSize:&actualSize 
                forWidth:rectWidth 
           lineBreakMode:breakMode];

CGSize size = [yourString sizeWithFont:[UIFont fontWithName:fontName size:actualSize]];
Nicholas M T Elliott