3

Very simple question, I'm trying to dynamically get the height of a UILabel, and it seems the boundingRectWithSize:options:context: is ignoring my second line. I've 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'm setting it up right, however this returns 17 (after getting the height and rounding up) regardless of whether it is 1 or 2 lines. Any help would be appreciated!

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

Bill L
  • 2,576
  • 4
  • 28
  • 55
  • Please add more part of the code. – Max Jul 02 '15 at 20:42
  • refer :- http://stackoverflow.com/questions/20068849/dynamically-getting-height-of-uilabel-according-to-text-return-different-value-f – Max Jul 02 '15 at 20:49
  • Possible duplicate of [boundingRectWithSize for NSAttributedString returning wrong size](http://stackoverflow.com/questions/13621084/boundingrectwithsize-for-nsattributedstring-returning-wrong-size) – mbelsky May 16 '16 at 06:06

1 Answers1

-1

I hope this helps. It is a simple solution. It's needed to round up 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;
}
93sauu
  • 3,770
  • 3
  • 27
  • 43