简体   繁体   中英

How to dynamically calculate the number of characters a UILabel holds before it gets truncated?

I have a UILabel that is configured with dynamic parameters:

textLabel.font = UIFont.systemFontOfSize(some_dynamic_size, weight: some_dynamic_font_weight)
textLabel.numberofLines = some_dynamic_number_lines
textLabel.frame = CGRectMake(0, 0, dynamic_width, dynamic_height)

How to calculate the number of characters this UILabel can hold before it gets truncated?

Calculate how tall the label would want to be given its font, text, and width. If that is taller than you want to make it, the text won't all fit.

The issue is that your label will be able to fit more or less text given on the font that you use and the size that it is set too. If you set that to a standard size say for instance San Francisco at 12pt then you will still have a varying amount of letters that can fit because not all letters are the same width for instance 'WWW' is allot bigger than ' lll ' but you could determine a "best estimate" by taking the average letter width. Then dividing the size of the label by that then you would have a general idea of how many letters could fit but you also need to account for the '...' that is inserted.

But I would suggest not concatenating at all and just make the text a variable size so it can shrink and show the whole word. I suggest looking into 'dynamic text' but I don't know what your application is so that may not be the best suggestion. Hope that helps 😜

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