Calculating number of lines of dynamic UILabel (iOS7)

Use suggested in documentation method :

- (CGRect)boundingRectWithSize:(CGSize)size options:(NSStringDrawingOptions)options attributes:(NSDictionary *)attributes context:(NSStringDrawingContext *)context NS_AVAILABLE_IOS(7_0);

E.g.

    CGSize maxSize = CGSizeMake(self.label.frame.size.width, MAXFLOAT);

    CGRect labelRect = [self.label.text boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:self.label.font} context:nil];

    NSLog(@"size %@", NSStringFromCGSize(labelRect.size));

I was having trouble using boundingRectWithSize directly on my UILabel's attributedText — it was not accounting for the wrap to multiple lines, (the returned height was always 17.5). To work around this, I had to use boundingRectWithSize on the UILabel's text property and pass in the attributes dictionary separately (and not via [self.myLabel.attributedText attributesAtIndex:0 effectiveRange:nil]).

CGRect labelSize = CGRectIntegral([self.myLabel.text     
    boundingRectWithSize:CGSizeMake(self.myLabel.frame.size.width, MAXFLOAT) 
    options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading
    attributes:@{NSFontAttributeName:self.myLabel.font, 
    NSParagraphStyleAttributeName:paragraphStyle} context:nil]);

Tags:

Ios

Uilabel

Ios7