Calculating UILabel Text Size Calculating UILabel Text Size ios ios

Calculating UILabel Text Size


All of the [NSString sizeWithFont...] methods are deprecated in iOS 7. Use this instead.

CGRect labelRect = [text                    boundingRectWithSize:labelSize                    options:NSStringDrawingUsesLineFragmentOrigin                    attributes:@{                     NSFontAttributeName : [UIFont systemFontOfSize:14]                    }                    context:nil];

Also see https://developer.apple.com/documentation/foundation/nsstring/1619914-sizewithfont.

UPDATE - example of boundingRectWithSize output

Per your comment I did a simple test. The code and output is below.

// code to generate a bounding rect for text at various font sizesNSString *text = @"This is a long sentence. Wonder how much space is needed?";for (NSNumber *n in @[@(12.0f), @(14.0f), @(18.0f)]) {    CGFloat fontSize = [n floatValue];    CGRect r = [text boundingRectWithSize:CGSizeMake(200, 0)                                  options:NSStringDrawingUsesLineFragmentOrigin                               attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]}                                  context:nil];    NSLog(@"fontSize = %f\tbounds = (%f x %f)",          fontSize,          r.size.width,          r.size.height);}

this produces the following output (note that the bounds change as expected as the font size gets larger):

fontSize = 12.000000    bounds = (181.152008 x 28.632000)fontSize = 14.000000    bounds = (182.251999 x 50.105999)fontSize = 18.000000    bounds = (194.039993 x 64.421997)


Length gets the number of characters. If you want to get the width of the text:

Objective-C

CGSize textSize = [label.text sizeWithAttributes:@{NSFontAttributeName:[label font]}];

Swift 4

let size = label.text?.size(withAttributes: [.font: label.font]) ?? .zero

This gets you the size. And you can compare the textSize.width of each label.


Another simple way to do this that I haven't seen mentioned yet:

CGSize textSize = [label intrinsicContentSize];

(This only works correctly after you have set the label's text and font, of course.)