How to calculate UILabel width based on text length?

Sheehan Alam picture Sheehan Alam · Aug 20, 2010 · Viewed 125.9k times · Source

I want to display an image next to a UILabel, however UILabel has variable text length, so I don't know where to place the image. How can I accomplish this?

Answer

Aaron Saunders picture Aaron Saunders · Aug 20, 2010
CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

this question might have your answer, it worked for me.


For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);