Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is UIFont sizeWithFont including blank space in its calculation?

I am setting a UILabels frame based on what is returned by UIFont sizeWithFont but for whatever reason when i use a custom font, the values that are returned include some padding as seen below.

When i use boldSystemFontOfSize the text is vertically aligned in the middle (which is what i want), but when i use fontWithName i end up with padding under the text. Any reason why sizeWithFont is adding in the padding?

enter image description here

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

** Edit **

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

float topPadding = [label.font ascender] - [label.font capHeight];
float bottomPadding = [label.font lineHeight] - [label.font ascender];
like image 552
AlBeebe Avatar asked Sep 13 '11 07:09

AlBeebe


1 Answers

Font is the only possible cause of this padding, but if you only need one-line labels, don't waste your time editing the font, just reduce the label's height by those few pixels after setting a proper frame by doing something like this:

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

Also, 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 just call:

[label sizeToFit];
like image 153
Filip Radelic Avatar answered Oct 21 '22 15:10

Filip Radelic