Search code examples
iphonecocoa-touchuikit

How to calculate the width of a text string of a specific font and font-size?


I have a UILabel that displays some chars. Like "x", "y" or "rpm". How can I calculate the width of the text in the label (it does not ues the whole available space)? This is for automatic layouting, where another view will have a bigger frame rectangle if that UILabel has a smaller text inside. Are there methods to calculate that width of the text when a UIFont and font size is specified? There's also no line-break and just one single line.


Solution

  • You can do exactly that via the various sizeWithFont: methods in NSString UIKit Additions. In your case the simplest variant should suffice (since you don't have multi-line labels):

    NSString *someString = @"Hello World";
    UIFont *yourFont = // [UIFont ...]
    CGSize stringBoundingBox = [someString sizeWithFont:yourFont];
    

    There are several variations of this method, eg. some consider line break modes or maximum sizes.