Why does UIFont sizeWithFont include a space in its calculation?

I set the UILabels frame based on what UIFont sizeWithFont returns, but for some reason, when I use my own font, the return values ​​include some additions, as shown below.

When I use boldSystemFontOfSize , the text is vertically aligned in the middle (this is what I want), but when I use fontWithName , I end up filling under the text, Any reason why sizeWithFont is added in addition?

enter image description here

Here is my code ...

CGRect frameLabel = label.frame; CGSize sizeLabel = [label.text sizeWithFont:label.font]; frameLabel.size.width = sizeLabel.width; frameLabel.size.height = sizeLabel.height; [label setBackgroundColor:[UIColor redColor]]; 

** Change **

I can calculate the top and bottom padding with this code and adjust the labels of frame.origin.y to vertically center my label where it should be

 float topPadding = [label.font ascender] - [label.font capHeight]; float bottomPadding = [label.font lineHeight] - [label.font ascender]; 
+6
source share
1 answer

The font is the only possible reason for this addition, but if you only need single-line labels, do not waste time editing the font, just reduce the height of the labels for these few pixels after setting the correct frame by doing something like this:

 label.frame = CGRectInset(label.frame, 0, bottomPadding); 

In addition, instead of:

 CGRect frameLabel = label.frame; CGSize sizeLabel = [label.text sizeWithFont:label.font]; frameLabel.size.width = sizeLabel.width; frameLabel.size.height = sizeLabel.height; 

You can simply call:

 [label sizeToFit]; 
+3
source

Source: https://habr.com/ru/post/897209/


All Articles