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

It works great for multi line strings as well.

Basically its a function that lets you see how big a string is going to be when rendered with a font and line break mode.

I use it in a few spots in my application when I have variable length text I want to display in a certain area.

By default a UILabel will center the text vertically. To have the text top aligned you need to size the label to be only the height required by the string that’s in it.

I use this method to do this.

And example of how I would use it to do that is as follows:

//Calculate the expected size based on the font and linebreak mode of your label
CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

You specify how big of an area you have to put the text in, and then this method tells you how much space it will take up (wrapping as required). Also if the string will overflow the bounds of the rect you provide you can tell and then decided how to display the text.

The reference to it not actually wrapping the text is there because this method doesn’t actually do anything to the text. It just virtually lays it out and returns how big of an area it would need to really lay it out.

its the responsibility of the label (or what ever container you are using for the text) to perform the wrapping/what ever else that needs to be done.

Hope that helps.

chris.

Leave a Comment