I use the code below to calculate the number of lines of string with limited width.
NSString *text = @"abcdefgh";
UIFont *font = [UIFont systemFontOfSize:15.0];
CGFloat h = [text suggestHeightWithFont:font width:320.0];
NSInteger lines = (h > font.lineHeight) ? h/font.lineHeight+1 : h/font.lineHeight;
NSLog(@"height %f, %f, number lines:%ld", h, font.lineHeight, (unsigned long)lines);
But I found that font.lineHeight
(log shows it is 17.900391) is larger than the font size which is set as 15.0
.
The log message shows:
height 17.900391, 17.900391, number lines:1
While there is no perfect line height, a good rule of thumb is to set it at approximately 150% of the font size. While there is no perfect line height, a good rule of thumb is to set it at approximately 150% of the font size.
If the value of the line-height property is smaller than the value of the font-size , text may overflow the element, and text on one line may overlap text on another line above or below it. It is often convenient to set the value of the line-height in the font shorthand property.
If your font size is 10px, your line height will be 10px, 18px, and 20px, respectively. Sets line height as a percentage of the font size of the element. If your font size is 10px, your line height will be 3px, 5px, and 11px respectively.
Line height can be expressed in a variety of units, including points, pixels, ems, and rems. Thinking in percentages is perhaps the easiest way of understanding the relationship between font size and line height. Setting a line height of 150% in a design application multiplies our font size by 1.5.
e.g. for font size 10
A might have ascender=10, descender=0
g might have ascender=5, descender=4
lineHeight = 14 + leading ... 14,5 maybe
Note that the numbers here were random and only given to better illustrate the issue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With