Attributed Text boundingRectWithSize returns wrong size

Very simple question, I am trying to get the height of the UILabel dynamically and it seems to be boundingRectWithSize:options:context:

ignoring my second line. I have pasted the relevant code below:

CGSize maximumLabelSize = CGSizeMake(self.frame.size.width,CGFLOAT_MAX);
return [self.attributedText boundingRectWithSize:maximumLabelSize options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;

      

I think I configured this correctly, but this returns 17 (after getting the height and rounding) no matter if it's 1 or 2 lines. Any help would be appreciated!

Edit: When using NSStringDrawingUsesFontLeading, it turns off my second line completely.

+3


source to share


1 answer


Hope this helps. This is a simple solution. It should have rounded off the expected height.



+ (void)adjust:(UILabel *)label withString:(NSString*)string withMaximumSize:(CGSize)maxSixe{

CGRect expectedLabelRect = [string boundingRectWithSize:maxSixe
                                                options:NSStringDrawingUsesLineFragmentOrigin
                                                 attributes:@{NSFontAttributeName: label.font}
                                                    context:nil];
expectedLabelRect.size.height = ceilf(expectedLabelRect.size.height);

//adjust the label the the new height.
CGRect newFrame = label.frame;
newFrame.origin.y += (newFrame.size.height - expectedLabelRect.size.height) * 0.5;
newFrame.size.height = expectedLabelRect.size.height;

label.numberOfLines = ceilf(newFrame.size.height/label.font.lineHeight);
label.frame = newFrame;
}

      

-1


source







All Articles