简体   繁体   中英

UILabel with constant size and dynamic font size depends on text

I have UILabel on my UIView. I always get various data for my label(from backend). I have some rect to display text on View (i set it as uilabel size, this size is constant).

How to set dynamic font for my UILabel for its size? I just need to display text data with actual font size, for my rect bounds. If text really long, and minimal font will wrap text - i need to apply minimal font size to display more text data.

(my label can be multi lines to be sized to const rect bounds)

There is property in UILable - adjustToFitWidth in xib, where you can give minimum font size. So if your text is getting longer then it will automatically reduce font size to adjust it within the label.

Note: whatever value given in adjustToFitWidth, is minimum limit, so your font size always be greater or equals to that value.

Enjoy Coding :)

I would do this in this way: Get the NSString character count. Based on that character count, calculate the size.

NSString *myString = @"Hello";
int myInt = myString.length;
float fontSize = PUT_A_VALUE_HERE / myInt;

You are going to play with the variable PUT_A_VALUE_HERE until you get desired results. After that, change the font size

[lblYourUILabel setFont:[UIFont fontWithName:fontName size:fontSize]];

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