Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find out width of truncated UILabel text

I have UILabel, which contains dynamic text. Sometimes text is too long to be shown and thus automagically truncated. How do I find out width of the visible part of truncated text?

sizeThatFits returns length of untruncated text, so at the moment I can only detect when truncation will be done. Need to know how much is visible, including those three dots. Any tips?

Clarification: when text is truncated, it's usually shorter than UILabel width.

like image 540
JOM Avatar asked Oct 11 '10 05:10

JOM


People also ask

How can I tell if UILabel is truncated Swift?

You can count the number of lines after assigning the string and compare to the max number of lines of the label. This is the nice answer for swift.

How do I change my UILabel text?

Changing the text of an existing UILabel can be done by accessing and modifying the text property of the UILabel . This can be done directly using String literals or indirectly using variables.


2 Answers

Robot K is correct.

If I was you I'd do the following:

  UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 24)];
  label.text = @"this is some really long text that i want in a small label";
  [view addSubview:label];

  CGSize size = [label.text sizeWithFont:label.font constrainedToSize:label.frame.size  
                 lineBreakMode:label.lineBreakMode];

This should give you a value less than 200 (taking into account the constrained max size and truncation method).

like image 63
Luke Avatar answered Oct 05 '22 04:10

Luke


I don't understand why the width would be different that the width of the UILabel if the text is being truncated. Regardless, you can use sizeWithFont:constrainedToSize: to calculate the size of a string with a given font but limited to a "constraining size".

like image 33
Kris Markel Avatar answered Oct 05 '22 04:10

Kris Markel