How to get the size of a NSString

This is a different approach. Find out the minimum size of the text so that it won’t wrap to more than one line. If it wraps to over one line, you can find out using the height.

You can use this code:

CGSize maximumSize = CGSizeMake(300, 9999);
NSString *myString = @"This is a long string which wraps";
UIFont *myFont = [UIFont fontWithName:@"Helvetica" size:14];
CGSize myStringSize = [myString sizeWithFont:myFont 
                           constrainedToSize:maximumSize 
                               lineBreakMode:self.myLabel.lineBreakMode];

300 is the width of the screen with a little space for margins. You should substitute your own values for font and size, and for the lineBreakMode if you’re not using IB.

Now myStringSize will contain a height which you can check against the height of something you know is only 1 line high (using the same font and size). If it’s bigger, you’ll need to cut the text. Note that you should add a … to the string before you check it again (adding the … might push it over the limit again).

Put this code in a loop to cut the text, then check again for the correct height.

Leave a Comment