3
votes

I create a UILabel with following code:

UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectZero];
textLabel.font = [UIFont systemFontOfSize:30];
textLabel.backgroundColor = [UIColor redColor];
textLabel.text = @"0";
[textLabel sizeToFit];
textLabel.center = CGPointMake(100, 100);
[self.view addSubview:textLabel];

and the textLabel.bounds.height seems higher than the text font actual height. like following: enter image description here

but because the designer marks the space of two UILabel based on real text size, so I can't just assign a value for two UILabel use designer's mark space, I need to run app in simulator to check it's correct.

I wan to know how to make UILabel sizeTofit to get the real height of text, no padding between text.

1

1 Answers

7
votes

There is extra room around the 0 in your example because the label has to take into account the entire set of metrics for the font, Cocoanetics has a nice illustration of this in their blog post "Understanding UIFont". For example, just running your code on my machine and putting a "g" next to the "0", we can see that the "g" almost touches the bottom of the label:

"0g" metrics

If you are implementing a label that can contain arbitrary text, your designer should account for this and not ask for the "real text size" of placeholder text—which may end up being inaccurate as we can see here when the placeholder is just "0". Ideally they would provide you with the baseline and font, that's all you need to have accurate results.

If you absolutely must measure the string precisely, NSString has the -sizeWith… method(s), NSAttributedString has -boundingRectWithSize:… and -size, and Core Text has CTFramesetterSuggestFrameSizeWithConstraints(). All of these have their own quirks and may not produce the results you're expecting, though.