Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force text to fit in UILabel vertically?

I know there are a lot of threads similar to this, but I've read all of them (as far as I can tell) and haven't seen the same problem I'm having.

I'm trying to get all of the text to show in a label VERTICALLY.

Let me explain - Fonts are not always created the same way, so while their total height may be the same (24pts, for example). However, the Ascender and Descender vary widely - one font may be mostly above the baseline, while another is mostly below. Therefore, the same text, with different fonts may not always show in the same view/label.

For example, see the screenshots below.

The first is Helvetica-Bold 300pts. The second is Apple Gothic 300pts.

Notice how the bottom of the "g" is cut off with Helvetica (and many other fonts too - try it, you'll see).

Helvetica-Bold300

AppleGothic

So my issue is this: I'd like to be able to see the entire text, regardless of the font. If the text in the "Helvetica" example could be moved up (and centered) within the label, it would solve my problem. To make it easier, I only need to display a single line.

Unfortunately, none of the solutions I've seen involve the descenders and ascenders of the font and figuring out how to draw the text within a Rect and not have it cropped. Note that the "VerticalAlignment" solutions in various threads don't fix this particular problem.

Does anyone have any ideas or solutions for this?

like image 335
wayneh Avatar asked Nov 04 '22 06:11

wayneh


1 Answers

The simplest way is to subclass UILabel and make use of NSString's - (CGSize)sizeWithFont:(UIFont *)font forWidth:(CGFloat)width lineBreakMode:(UILineBreakMode)lineBreakMode method found in the NSString UIKit additions.

You could override - (void)setFont in your sublcass, test if the font size will work with in the view's rect, and if it is too big, make it smaller until it fits.

like image 123
sosborn Avatar answered Nov 09 '22 08:11

sosborn