A very serious question, how do you normally set the height of UILabel?

I’ve seen quite a few common ones:

UILabel *lb = [UILabel new];
lb.text = @"gyjq";
lb.font = [UIFont systemFontOfSize:30];
lb.backgroundColor = [UIColor clearColor];
[self.view addSubview:lb];
lb.frame = CGRectMake(10, 100, 200, 30);Copy the code

Can you see what’s wrong with the code above?

If you run the above code on a real machine, you get the following display:

In the picture above, the bottom of each letter is “truncated” with a small part cut off. If the text is of other English letters, it will appear normal. The letters G, Y, J and Q will be truncated, but if the text is of Mixed Chinese and English, the result will be normal again.

When I use App at ordinary times, I have found interception in many App interfaces.

The problem is that the Frame height of UILabel cannot be simply the same as the Font height. UILabel has different requirements for Frame height under different Font Settings. In most cases, the Frame height is higher than the Font height.

Of course we can use other apis to get the correct UILabel height:

SuggestedSize = [lb sizeThatFits:CGSizeMake(200, 30)]; suggestedSize = [lb sizeThatFits:CGSizeMake(200, 30)]; // method 2 [lb sizeToFit]; NSString* text = @"gyjq"; CGSize labelSize = [text sizeWithFont:lb.font constrainedToSize:CGSizeMake(200.f, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping]; CGSize size = [text sizeWithAttributes:@{NSFontAttributeName: lb.font}]; CGRect frame = lb.frame; frame.size.width = size.width; frame.size.height = size.height; lb.frame = frame;Copy the code

The sizes obtained by the above four methods all display the correct text content, but the height of the size is different.

In the first and second ways, if the font size is set to 30, the result is:

(width = 57, height = 36)

The results of the third and fourth methods are:

(width = 56.8652344, height = 35.8007813)

And depending on the font size, the extra space beyond the font height also varies:

For example, when font size is 13, the height is calculated as 16; when font size is 20, the height is calculated as 24. Therefore, when setting the height of UILabel, it is not easy to add arbitrary value on the basis of font height.

When I browse the web, I find the same problem on the Web side, such as the label display in the personal signature file of Zhihu web edition:

Review images

The letter G is also truncated.

I guess the reason is that the text rendering engine needs to reserve a small space at the top and bottom of the label when rendering a line of text, probably for the sake of typographical aesthetics.

Welcome to our official account: