Replicate the actualFontSize pointer return in Deprecated sizeWithFont:minFontSize:actualFontSize to get the change in font size?

StackOverflow https://stackoverflow.com/questions/22156095

Вопрос

So,

in sizeWithFont:minFontSize:actualFontSize, we pass a pointer for actualFontSize which can then be used to shrink the font within a label. As in :

[s sizeWithFont:self.font
                minFontSize:minimumScaleFactor
                actualFontSize:&actualFontSize
                    forWidth:width
                lineBreakMode:lineBreakMode];

So now, we can do self.frame.font.pointSize = actualSize to modify the font size. My question is : Now that sizeWithFont is deprecated, how do I get this pointer back?

Basically, the recommended method to replace it is boundingRectWithSize :

[s boundingRectWithSize:CGSize(width,CGFLOAT_MAX)
                options:(NSStringDrawingUsesLineFragmentOrigin)
                attributes://An NSDictionary with font
                context:nil];

But as you can see, it only returns the size. I thought of doing something like :

changeInFontSize = (newSize.height - oldSize.height) + (newSize.width - oldSize.width)
                   -------------------------------------------------------------------
                                                  2

But this doesn't really give me the answer I want. Could someone help me about how to do this? To be precise - I need the difference in the font size to change the current font size!

Это было полезно?

Решение

The problem is that sizeWithFont method reduces the fontsize as needed. So if the function used a smaller font size, how do you know which size it used? That's the actualFontSize for!! From the documentation:

Although it computes where line breaks would occur, this method does not actually wrap the text to additional lines. If the entire string does not fit within the given width using the initial font size, this method reduces the font size until the string does fit or until it reaches the specified minimum font size.

The new recommended method boundingRectWithSize does not reduce the fontsize. So if the function does NOT reduce the fonsize, meaning, it will use the size you specify in attributes, there's no need to return the actual size used (because it's exactly the one you specified, hence, you already know it).

EDIT:
If you want to calculate the font size needed to fit in some predefined bounding box, you would need to test with a few point sizes and calculate the one that fits best. Check this link for some examples (the last answer on the link looks interesting to optimize efficiency)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top