简体   繁体   中英

Adjust the font of UILabel so that the text fits within the label's bounds

My view controller has a UILabel. It displays a dollar amount to the user. I have a default size that I like the dollar amount to be displayed as, shown below

好

When the amount is too large, some text is replaced with "..."

坏

I want to adjust the text of the UILabel (make it smaller) such that the point size of the text is just enough to not cause the dots to appear. Is there some quick math I can do to accomplish this?

Use this:

UILabel * label = // your label

// update from @rmaddy and @z s
label.adjustsFontSizeToFitWidth = YES;
label.minimumScaleFactor = 0.5;

This means that you'll allow your text to shrink to up to half its size before truncating. Adjust accordingly.

If you're working in a pre iOS 7 environment, you can also use:

UILabel * label;
label.minimumFontSize = 14;

To set a specific minimum font size; however, this has been deprecated since iOS 7

No need for you to make the math, the system-provided API can do it for you. In Interface Builder, set the label's autoshrink to minimum scale factor of 0.7 (or whatever value fits your need). Text will now shrink as necessary.

在此输入图像描述

label.adjustsFontSizeToFitWidth = YES;
label.numberOfLines = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM